golang struct & map
- 匿名 struct,當你不想要污染code,只想在局部使用時,可以應用匿名 struct
-
func main() { p1 := struct { first string last string age int }{ first: "James", last: "Bond", age: 32, } fmt.Println(p1) }
- Embedded structs
-
type person struct { first string last string age int } type secretAgent struct { person ltk bool } func main() { sa1 := secretAgent{ person: person{ first: "James", last: "Bond", age: 32, }, ltk: true, } p2 := person{ first: "Miss", last: "Moneypenny", age: 27, } fmt.Println(sa1) fmt.Println(p2) fmt.Println(sa1.first, sa1.last, sa1.age, sa1.ltk) fmt.Println(p2.first, p2.last, p2.age) }
遷入的struct,會被 promoted,可以直接sa1.first,而不用sa1.person.first
- 實際創建 struct 並利用 map 去印出內容
-
package main import "fmt" type person struct { first string last string favorite []string } func main() { p1 := person{ first: "James", last: "Bond", favorite: []string{ "howhow", "tree", }, } p2 := person{ first: "Lisa", last: "Wang", favorite: []string{ "Gan", "Man", }, } m := map[string]person{ p1.last: p1, p2.last: p2, } fmt.Println("----------") for _, value := range m { fmt.Println(value.first) fmt.Println(value.last) for i, k := range value.favorite { fmt.Println(i, k) } fmt.Println("----------") } }
- note