Skip to content

Instantly share code, notes, and snippets.

@weaming
Last active December 6, 2022 16:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weaming/5cd2b4a560c3fa76845566e6c6d64d73 to your computer and use it in GitHub Desktop.
Save weaming/5cd2b4a560c3fa76845566e6c6d64d73 to your computer and use it in GitHub Desktop.
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>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment