這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
寫了一個月的外掛程式,發現interface這個關鍵詞幾乎沒怎麼用,然後好奇,開啟了gjson的源碼,發現gjson的源碼用的也很少,最多的用法是相當於java中的object。我開始思索,為什麼需要Interface,而不是一個object(寫到這裡,我想起了被C語言裡void* 支配的恐懼)。
個人感覺interface中翻譯成介面是有點令人費解。正如handler譯成控制代碼,貌似當時是寫錯了,勾被看錯成句,handler,勾柄,就是門把手,socket就是插座的意思。
對interface(介面)最基本的印象,是fmt.Println這個方法,當時就覺得很神奇,真要實現了String方法,就可以被列印出來。現在寫多了程式,就發現,“介面即合約”。
我看到IO裡reader/writer的實現,都是用的interface,我也試者去編寫自己的 reader/writer,然後當做一個變數去傳遞。也許是我最近的工作都是在一個包裡進行、也不用進行傳遞,更不用說什麼struct的交換。
更權威的總結如下:
An interface is a kind of contract which the implementing type(s) must fulfill. Interfaces describe the behaviorof types, what they can do. They completely separate the definition of what an object can do from how it does it, allowing distinct implementations to be represented at different times by the same interface variable, which is what polymorphism essentially is.
Writing functions so that they accept an interface variable as a parameter makes them more general.
《The Way to Go》
野生翻譯如下:
介面是一種必須要全部實現(所申明函數)的約束。介面定義了類型的行為,即:“它們可以做什麼”。與“一個對象怎麼去做”的定義完全不一樣,他允許在不同的時間裡,相同的介面變數代表著不同的實現,這就是Go多態性的本質。寫方法時,讓他們接收介面類型,就像平常的傳遞一個參數那樣。
總結interface
寫了這麼久的Golang,我在想,以前java/C++那一套,建構函式,重載,也並不是真的就那麼的必要。但是無比懷念Java的泛型,還有gradle。