Skip to content

Instantly share code, notes, and snippets.

@neguse
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neguse/b4b3358f2897949a89a7 to your computer and use it in GitHub Desktop.
Save neguse/b4b3358f2897949a89a7 to your computer and use it in GitHub Desktop.
composite literal( https://golang.org/ref/spec#Composite_literals ) で入れ子になっているanonymous structをリテラルとして書きたかった
package main
import (
"encoding/json"
"fmt"
)
type Struct struct {
Inner struct {
Value string
}
}
type Struct2 struct {
Inner Inner;
}
type Inner struct {
Value string
}
func main() {
// こう書きたいけど
// v := Struct { { "value" } }
// json.go:15: missing type in composite literal
// なのでこうせざるをえない
{
v := Struct {}
v.Inner.Value = "value"
b, _ := json.Marshal(&v)
bs := string(b[:])
fmt.Print(bs)
}
// あるいはこう
{
v2 := Struct { Inner { "value" } }
b, _ := json.Marshal(&v2)
bs := string(b[:])
fmt.Print(bs)
}
// ちなみにUnmarshalするだけならいける
{
v3 := Struct{}
json.Unmarshal([]byte(`{"Inner":{"Value":"value"}}`), &v3)
b, _ := json.Marshal(&v3)
bs := string(b[:])
fmt.Print(bs)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment