DAY 16
1
Software Development

## Struct 結構

``````type ContactDetails struct {
Email   string
Subject string
Message string
}
``````

``````type Todo struct {
Title string
Done  bool
}

type TodoPageData struct {
PageTitle string
Todos     []Todo
}
``````

``````type ContactDetails struct {
Email, Subject, Message string
}
``````

# 結構體嵌入與匿名成員

``````//點
type Point struct {
X, Y int
}
//圓
type Circle struct {
Center Point
}
//車輪
type Wheel struct {
Circle Circle
Spokes int
}
``````

``````var w Wheel
w.Circle.Center.X = 8
w.Circle.Center.Y = 8
w.Spokes = 20
``````

``````type Circle struct {
Point
}

type Wheel struct {
Circle
Spokes int
}
``````

``````var w Wheel
w.X = 8            // 等同於 w.Circle.Point.X = 8
w.Y = 8            // 等同於 w.Circle.Point.Y = 8
w.Spokes = 20
``````

``````w = Wheel{
Circle: Circle{
Point:  Point{X: 8, Y: 8},
},
Spokes: 20, //特別注意，最後一個成員結尾的逗點是必要的
}
//簡寫為一行
w = Wheel{Circle{Point{8, 8}, 5}, 20}
``````

# 輸出

``````type T struct {
a int
b float64
c string
}
t := &T{ 360, 9.2, "I'm a string." }
``````

``````fmt.Printf("%v\n", t)
fmt.Printf("%+v\n", t)
fmt.Printf("%#v\n", t)
``````
• `%v`：單純把內容都印出來，會得到`&{7 -2.35 I'm a string.}`
• `%+v`：除了值以外，還有欄位名稱，得到`&{a:7 b:-2.35 c:I'm a string.}`
• `%#v`：可以得到最多資訊，連結構體的名稱、所在的函數都會一起印出，得到`&main.T{a:7, b:-2.35, c:"I'm a string."}`

# Reference

### 2 則留言

0
alfredisabug
iT邦新手 5 級 ‧ 2018-10-23 08:52:49

Bater iT邦新手 5 級 ‧ 2018-10-23 21:28:31 檢舉

0
eric19740521
iT邦新手 4 級 ‧ 2020-08-01 16:45:10
``````w = Wheel{
Circle{
Point{8, 8},
5},
20,
}
``````

``````w = Wheel{
Circle{
Point{8, 8},
5},
20}
``````