Last active
August 29, 2015 14:05
-
-
Save neguse/b4b3358f2897949a89a7 to your computer and use it in GitHub Desktop.
composite literal( https://golang.org/ref/spec#Composite_literals ) で入れ子になっているanonymous structをリテラルとして書きたかった
This file contains 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" | |
) | |
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