1. 程式人生 > >【go學習筆記】interface妙用

【go學習筆記】interface妙用

空interface

空interface(interface{})不包含任何的method,正因為如此,所有的型別都實現了空interface。空interface對於描述起不到任何的作用(因為它不包含任何的method),但是空interface在我們需要儲存任意型別的數值的時候相當有用,因為它可以儲存任意型別的數值。它有點類似於C語言的void*型別

// 定義a為空介面
var a interface{}
var i int = 5
s := "Hello world"
// a可以儲存任意型別的數值
a = i
a = s

一個函式把interface{}作為引數,那麼他可以接受任意型別的值作為引數,如果一個函式返回interface{},那麼也就可以返回任意型別的值。是不是很有用啊!