Go結構體巢狀

2021-10-05 18:56:04 字數 1242 閱讀 2116

package main

import

"fmt"

//結構體巢狀

/*結構體巢狀: 乙個結構體中的字段,是另乙個結構體型別

has a

*/func

main()

b1.bookname =

"西遊記"

b1.price =

45.8

s1 := student

s1.name =

"小明"

s1.age =

21 s1.book = b1

fmt.

println

(b1)

fmt.

println

(s1)

fmt.

printf

("學生姓名: %s, 學生年齡: %d, 看的書:《%s》, 書的**: %.2f\n"

,s1.name,s1.age,s1.book.bookname,s1.book.price)

//或者:

//s2 := student}

s2 := student,}

fmt.

printf

("學生姓名: %s, 學生年齡: %d, 看的書:《%s》, 書的**: %.2f\n"

,s2.name,s2.age,s2.book.bookname,s2.book.price)

b4 := book

s3 := student2

fmt.

println

(s3.name,s3.age)

fmt.

println

("\t"

,s3.book.bookname,s3.book.price)

}//1.定義乙個書的結構體

type book struct

//2.定義學生的結構體

type student struct

//結構體指標(建議使用),不用再拷貝乙份,節省記憶體

type student2 struct

結果:

}學生姓名: 小明, 學生年齡:

21, 看的書:《西遊記》, 書的**:

45.80

學生姓名: 狗子, 學生年齡:

21, 看的書:《紅樓夢》, 書的**:

45.85

李四 18

呼嘯山莊 76.8

go語言基礎 結構體巢狀

go語言當中的聚合和繼承都是模擬出來的,子類是可以使用父類裡的字段或功能 結構體的巢狀 type a struct type b struct type c struct b b b.a.name,c c b.name,packagemain import fmt typeperson5struct...

結構體巢狀結構體名

結構體巢狀結構體名 前一段時間在看ddk中例子的時候,看到這樣的的結構體定義 typedef struct common device data common device data,pcommon device data typedef struct pdo device data pdo dev...

結構體中巢狀結構體

結構體的巢狀問題 結構體的自引用 self reference 就是在結構體內部,包含指向自身型別結構體的指標。結構體的相互引用 mutual reference 就是說在多個結構體中,都包含指向其他結構體的指標。1.1不使用typedef時 錯誤的方式 struct tag 1 這種宣告是錯誤的,...