Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example provides use case marshalling map with custom key as a structure to json
package main
import (
"encoding"
"encoding/json"
"fmt"
)
type key struct {
this string
another string
t chan int
}
func(k key) MarshalText() ([]byte, error) {
return []byte(fmt.Sprint(k)), nil
}
var _ encoding.TextMarshaler = new(key)
func main() {
key1 := key{
this: "1",
another: "1",
}
key2 := key{
this: "2",
another: "2",
}
mm := make(map[key]string)
mm[key1] = "1"
mm[key2] = "2"
mm[key{}] = "empty"
b, err := json.Marshal(mm)
if err != nil {
panic(err)
}
fmt.Println(string(b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment