GO型別巢狀

2021-07-28 20:11:16 字數 3806 閱讀 9811

在go結構體型別中巢狀乙個其他的型別可以到達繼承的目的。

語法:struct

func

(ffather)speek(x

string)

func

(f*father)grow()

type

child

struct

func

main()

varc=child

//由於c.father型別是值型別,所以將f賦值給c.father時,會發生值拷貝過程

c.speek("hello

world")

//子類物件直接呼叫父類的speek方法

fmt.println(c)
c.grow()

//子類物件呼叫父類的grow方法,但是grow方法的接收器是c.father,而不是c,更不是f

fmt.println("c

=",c)

fmt.println("f

=",f)

}

編譯執行:

c:/go/bin/go.exe run test5.go [e:/project/go/proj/src/test]

hello world

170}

c = 170}

f =

成功: 程序退出** 0.

example2:巢狀型別father,檢視子型別child的方法集

package

main

import

"fmt"

type

father

struct

func

(ffather)speek(x

string)

func

(ffather)grow()

type

child

struct

type

speekgrower

inte***ce

func

main()

varc=child

//由於c.father型別是值型別,所以將f賦值給c.father時,會發生值拷貝過程

varsgspeekgrower

sg=c  //型別child
sg.speek("thisisa

test.")

sg=&c  //型別*child
sg.speek("thisisa

test.")

}
編譯執行:
c:/go/bin/go.exe run test7.go [e:/project/go/proj/src/test]

this is a test.

this is a test.

成功: 程序退出** 0.

package

main

import

"fmt"

type

father

struct

func

(ffather)speek(x

string)

func

(f*father)grow()

type

child

struct

type

speekgrower

inte***ce

func

main()

varc=child

//由於c.father型別是值型別,所以將f賦值給c.father時,會發生值拷貝過程

varsgspeekgrower

sg=c  //因為c型別是child,值型別,賦值給介面時,會發生值拷貝,所以,該操作成功的前提是child的所有方法都必須是值接收器
sg.speek("thisisa

test.")

sg=&c
sg.speek("thisisa

test.")

}
編譯執行: 

c:/go/bin/go.exe run test7.go [e:/project/go/proj/src/test]

# command-line-arguments

.\test7.go:32: cannot use c (type child) as type speekgrower in assignment:

child does not implement speekgrower (grow method has pointer receiver)

錯誤: 程序退出** 2.

總結:通過上面兩個例子,可以看出,當巢狀型別是father時,型別child的方法集只包括father中接收器為值的方法;型別*child的方法集包含了father中所有的方法,所以*child實現了上述的介面。

example3:巢狀型別*father,檢視子型別child的方法集

package

main

import

"fmt"

type

father

struct

func

(ffather)speek(x

string)

func

(f*father)grow()

type

child

struct

type

speekgrower

inte***ce

func

main()

varc=child

varsgspeekgrower

sg=c

//型別child,這裡會發生值拷貝

sg.speek("thisisa

test.")

sg=&c

//型別*child,這裡會發生引用傳遞

sg.speek("thisisa

test.")

}
編譯執行:

c:/go/bin/go.exe run test7.go [e:/project/go/proj/src/test]

this is a test.

this is a test.

成功: 程序退出** 0.

ok,通過上面的案例可以看出,當內嵌型別是*father時,型別child和*child都包含了speek和grow方法,所以實現了speekgrower介面。

Go結構體巢狀

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.p...

巢狀從屬模板型別

今天在看spdlog的原始碼的時候,發現了乙個重要的知識點 巢狀從屬模板型別,示例 如下 struct synchronous factory templateauto rotating logger mt 中的create函式就屬於模板從屬型別,因為它是模板類性factory 裡面的模板函式,此時...

go語言基礎 結構體巢狀

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