Golang學習筆記 介面和錯誤

2021-09-26 20:33:27 字數 1726 閱讀 3450

go介面定義了方法後,其它型別只要實現了這些方法就是實現了介面。go語言中介面型別的獨特之處在於它是滿足隱式實現的鴨子型別。所謂鴨子型別說的是:只要走起路來像鴨子,叫起來也像鴨子,那麼就可以把它當作鴨子。

type person inte***ce

type student struct

type worker struct

func

(student student)

speak()

func

(worker worker)

speak()

func

main()

person.

speak()

//i am worker

person=student

person.

speak()

//i am student

}

有時候物件和介面之間太靈活了,導致我們需要人為地限制這種無意之間的適配。常見的做法是定義乙個含特殊方法來區分介面。比如runtime包中的error介面就定義了乙個特有的runtimeerror方法,用於避免其它型別無意中適配了該介面:

type error inte***ce

在go中只有inte***ce的型別和值都為nil時,inte***ce==nil才為true,所以我們在函式中返回乙個inte***ce時,如果想返回nil,需要直接返回nil而不是返回結構體nil指標。

func

main()

data2=data

println

(data2==

nil)

//false

data2=

nilprintln

(data2==

nil)

//true

}

型別斷言是將介面型別轉換為具體型別,型別斷言分為安全型別斷言和非安全型別斷言,非安全型別斷言失敗時會發生異常,安全型別斷言則可以通過返回值判斷型別斷言是否失敗。

type myinte***ce inte***ce

type mystruct struct

func

(obj *mystruct)

sayhello()

func

newmystruct

() myinte***ce

}func

main()

//非安全型別斷言

obj2:=

newmystruct()

.(*mystruct)

obj2.

sayhello()

}

錯誤是go的內建介面,其定義如下:

type

error

inte***ce

對於簡單的錯誤,我們可以使用內建的errors.new生成乙個errorstring,對於複雜的錯誤,我們可以新建乙個結構體實現error介面。

func

divide

(vardividee int

, vardivider int)(

int,

error

)else

}func

main()

else

}

Golang學習筆記 十六 錯誤機制

在go語言中,除基本資料型別 int,float,boolean,string 複合型 struct,array 和引用型別 slice,map,指標,channel,function 外,還有一種內建的資料型別 error。error是go語言的內建型別,因此就像int等型別一樣,不需要引用任何包...

Golang學習筆記 物件導向介面封裝

package utils import fmt 定義結構體 type familyaccount struct 編寫要給工廠模式的構造方法 func newfamilyaccount familyaccount 主體業務邏輯 func this familyaccount initmainpage...

Golang學習筆記

如果乙個method的receiver是 t,你可以在乙個t型別的例項變數v上面呼叫這個method,而不需要 v去呼叫這個method 即不需要 v method 如果乙個method的receiver是t,你可以在乙個 t型別的變數p上呼叫這個method,而不需要 p去呼叫這個method。i...