Go不是一種典型的OO語言,它在語法上不支持類和繼承的概念。 沒有繼承是否就無法擁有多態行為了呢?答案是否定的,Go語言引入了一種新類型—Interface,它在效果上實現了類似於C++的「多態」概念,雖然與C++的多態在語法上並非完全對等,但至少在最終實現的效果上,它有多態的影子。
那麼,Go的Interface類型到底是什麼呢?怎麼使用呢?這正是本篇筆記試圖說明的問題。
1. Method(s) in Go
在說明Interface類型前,不得不先用Go的method(s)概念來熱身,因為Go語言的interface與method(s)這兩個語法有非常緊密的聯繫。雖然Go語言沒有類的概念,但它支持的數據類型可以定義對應的method(s)。本質上說,所謂的method(s)其實就是函數,只不過與普通函數相比,這類函數是作用在某個數據類型上的,所以在函數簽名中,會有個receiver來表明當前定義的函數會作用在該receiver上。
關於methods的精確語法規範,可以參考language specification或Effective Go中的說明,這裡略過。
注意:Go語言支持的除Interface類型外的任何其它數據類型都可以定義其method(而並非只有struct才支持method),只不過實際項目中,method(s)多定義在struct上而已。
在struct類型上定義method(s)的語法特性與C++中的struct支持的語法非常類似(c++中的struct定義了數據,此外也支持定義數據的操作方法),從這一點來看,我們可以把Go中的struct看作是不支持繼承行為的輕量級的「類」。
2. What is Interface type in Go ?
GoLang官網language specification文檔對interface type的概念說明如下:An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface. The value of an uninitialized variable of interface type is nil.
說實話,這段說明對新手來說比較晦澀,這正是本篇筆記試圖解釋清楚的地方。
