[ Go ] 11. Structs
副標題靈波(●´∀`)ノ♡
Sep 9, 2018 · 2 min read
struct 可以把多個資料整理在一起:
輸出為: {1 2} 1 2
上述例子將 x 與 y 整理至 Str 這個 struct 中,並在輸出時使用 . 取得裡面的值。
可以發現在 struct 上方有一行以該結構名稱開頭的註解,它並非必要的,不過可能會跳出警告訊息:
exported type <struct name> should have comment or be unexported指標 X 結構
struct 也可以使用指標:
輸出為:
&{1 2} 1 2
&{1 2} 1 2在上方例子中,因為 dataPtr 是指標,因此要取得其 x 值時,理論上要用 (*dataPtr).x ,但是 Go 也接受 dataPtr.x 的用法。
宣告變數時,可選擇只初始化特定變數,延續上方例子,若只想初始化 y 可以這樣寫:
data := Str{y: 12} // {0 12}new( ) 和 串列結構
- 可以使用
new( <struct type> )來初始化struct,會回傳該結構的指標 - 結構內的值可以是該結構本身,因此可以實現串列結構:
輸出為:
data: &{0 0}
node.point: &{1 2}
node.next.point: &{3 4}