Created
February 28, 2020 07:17
-
-
Save dennypenta/866baad9c1a3eac5ab7ab76611fa0cfa to your computer and use it in GitHub Desktop.
Example provides use case marshalling map with custom key as a structure to json
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" | |
"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