diff --git a/struct/anonymousField.go b/struct/anonymousField.go new file mode 100644 index 0000000..3e26890 --- /dev/null +++ b/struct/anonymousField.go @@ -0,0 +1,36 @@ +package main + +import "fmt" + +type SampleStruct1 struct { + Id int64 + Name string +} + +type SampleStruct2 struct { + SampleStruct1 + Address string +} + + +type SampleStruct3 struct { + SampleStruct1 + // SampleStruct1 // NG! + Address string +} + + +func main() { + v1 := SampleStruct2{SampleStruct1{1, "taro"}, "address"} + fmt.Println(v1) // {{1 taro} address} + + v2 := SampleStruct2{} + fmt.Println(v2) // {{0 } } + v2.Id = 2 + v2.Name = "jiro" + v2.Address = "address2" + fmt.Println(v2) // {{2 jiro} address2} + + v3 := SampleStruct2{ SampleStruct1: SampleStruct1{1, "taro"} } + fmt.Println(v3) // {{1 taro} } +} diff --git a/struct/json.go b/struct/json.go new file mode 100644 index 0000000..f2b07f5 --- /dev/null +++ b/struct/json.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" + "encoding/json" +) + +type SampleStruct1 struct { + Id int64 + Name string +} + + +type SampleStruct2 struct { + TestName string `json:"test_name"` +} + + +func main() { + v1 := SampleStruct1{1, "taro"} + if data, err := json.Marshal(v1); err == nil { + fmt.Printf("%s\n", data) // {"Id":1,"Name":"taro"} + + v2 := SampleStruct1{} + if err := json.Unmarshal(data, &v2); err == nil { + fmt.Println(v2) // {1 taro} + } + } else { + fmt.Println(err) + } + + v3 := SampleStruct2{} + if err := json.Unmarshal([]byte("{ \"test_name\": \"hoge-\" }"), &v3); err == nil { + fmt.Println(v3) // {hoge-} + } else { + fmt.Println(err) + } +} diff --git a/struct/struct1.go b/struct/struct1.go new file mode 100644 index 0000000..b41c7ae --- /dev/null +++ b/struct/struct1.go @@ -0,0 +1,28 @@ +package main + +import "fmt" + +type SampleStruct struct { + Id int64 + Name string +} + + +func main() { + v1 := SampleStruct{1, "taro"} + fmt.Println(v1) // {Id:1 Name:taro} + hoge(v1) + // 値渡し + fmt.Println(v1) // {Id:1 Name:taro} + + + v2 := SampleStruct{ Name: "jiro" } + fmt.Println(v2) // {0 jiro} +} + +func hoge(v SampleStruct) { + fmt.Println(v) // {Id:1 Name:taro} + v.Id = 2 + fmt.Println(v) // {Id:2 Name:taro} +} + diff --git a/struct/struct2.go b/struct/struct2.go new file mode 100644 index 0000000..a5f6ec6 --- /dev/null +++ b/struct/struct2.go @@ -0,0 +1,24 @@ +package main + +import "fmt" + +type SampleStruct struct { + Id int64 + Name, Address string +} + + +func main() { + v1 := SampleStruct{1, "taro", "address"} + fmt.Println(v1) // {Id:1 Name:taro Address:address} + + v2 := SampleStruct{1, "taro", "address"} + v3 := SampleStruct{1, "jiro", "address"} + fmt.Println(v1 == v2) // true + fmt.Println(v1 == v3) // false + p1 := &v1 + fmt.Printf("%p\n", p1) + (*p1).Id = 2 + fmt.Println(*p1) // {Id:2 Name:taro Address:address} + fmt.Println(v1) // {Id:2 Name:taro Address:address} +}