Last active
December 6, 2022 16:22
-
-
Save weaming/5cd2b4a560c3fa76845566e6c6d64d73 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"strings" | |
) | |
const DASH = "-" | |
type Pair struct { | |
Base, Quote string | |
} | |
func (p *Pair) String() string { | |
return p.Base + DASH + p.Quote | |
} | |
func (p Pair) MarshalText() ([]byte, error) { | |
return []byte(p.String()), nil | |
} | |
func (p *Pair) UnmarshalText(bytes []byte) error { | |
xs := strings.SplitN(string(bytes), DASH, 2) | |
if len(xs) != 2 { | |
return fmt.Errorf("invalid pair: %s", string(bytes)) | |
} | |
p.Base, p.Quote = xs[0], xs[1] | |
return nil | |
} | |
func main() { | |
// do NOT use pointer as map key | |
m1 := map[Pair]float64{} | |
m1[Pair{Base: "BTC", Quote: "USDT"}] = 1 | |
m1[Pair{Base: "ETH", Quote: "USDT"}] = 2 | |
fmt.Printf("%+v\n", m1) | |
bs, e := json.Marshal(m1) | |
fmt.Println(string(bs), e) | |
// CAN NOT use pointer as map key | |
m2 := map[Pair]float64{} | |
e = json.Unmarshal(bs, &m2) | |
fmt.Println(m2, e) | |
} | |
/* | |
OUTPUT: | |
map[{Base:BTC Quote:USDT}:1 {Base:ETH Quote:USDT}:2] | |
{"BTC-USDT":1,"ETH-USDT":2} <nil> | |
map[{BTC USDT}:1 {ETH USDT}:2] <nil> | |
*/ |
Author
weaming
commented
Dec 6, 2022
- https://stackoverflow.com/questions/21064244/structs-as-keys-in-go-maps
- https://stackoverflow.com/questions/55335296/problem-with-marshal-unmarshal-when-key-of-map-is-a-struct
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment