interface簡介
Go 語言以簡單易上手而著稱,它的文法非常簡單,熟悉 C++,Java 的開發者隻需要很短的時間就可以掌握 Go 語言的基本用法。
interface 是 Go 語言裡所提供的非常重要的特性。一個 interface 裡可以定義一個或者多個函數,例如系統自帶的 io.ReadWriter 的定義如下所示:
type ReadWriter interface {
Read(b []byte) (n int, err error)
Write(b []byte) (n int, err error)
}
任何類型隻要它提供了 Read 和 Write 的綁定函數實作,Go 就認為這個類型實作了這個 interface(duck-type),而不像 Java 需要開發者使用 implements 标明。
然而 Go 語言的 interface 在使用過程中卻有一個特别坑的特性,當你比較一個 interface 類型的值是否是 nil 的時候,這是需要特别注意避免的問題。
一次真實的踩坑
這是我們在 GoWorld分布式遊戲伺服器 的開發中,碰到的一個實際的 bug。由于 GoWorld 支援多種不同的資料庫(包括 MongoDB,Redis 等)來儲存服務端對象,是以 GoWorld 在上層提供了一個統一的對象存儲接口定義,而不同的對象資料庫實作隻需要實作
EntityStorage
接口所提供的函數即可。
// EntityStorage defines the interface of entity storage backends
type EntityStorage interface {
List(typeName string) ([]common.EntityID, error)
Write(typeName string, entityID common.EntityID, data interface{}) error
Read(typeName string, entityID common.EntityID) (interface{}, error)
Exists(typeName string, entityID common.EntityID) (bool, error)
Close()
IsEOF(err error) bool
}
以一個使用 Redis 作為對象資料庫的實作為例,函數
OpenRedis
連接配接 Redis 資料庫并最終傳回一個
redisEntityStorage
對象的指針。
// OpenRedis opens redis as entity storage
func OpenRedis(url string, dbindex int) *redisEntityStorage {
c, err := redis.DialURL(url)
if err != nil {
return nil
}
if dbindex >= 0 {
if _, err := c.Do("SELECT", dbindex); err != nil {
return nil
}
}
es := &redisEntityStorage{
c: c,
}
return es
}
在上層邏輯中,我們使用
OpenRedis
函數連接配接 Redis 資料庫,并将傳回的
redisEntityStorage
指針指派給一個
EntityStorage
接口變量,因為
redisEntityStorage
對象實作了
EntityStorage
接口所定義的所有函數。
var storageEngine StorageEngine // 這是一個全局變量
storageEngine = OpenRedis(cfg.Url, dbindex)
if storageEngine != nil {
// 連接配接成功
...
} else {
// 連接配接失敗
...
}
上面的代碼看起來都很正常,
OpenRedis
在連接配接 Redis 資料庫失敗的時候會傳回 nil,然後調用者将傳回值和 nil 進行比較,來判斷是否連接配接成功。這個就是 Go 語言少有的幾個深坑之一,因為不管
OpenRedis
函數是否連接配接 Redis 成功,都會運作連接配接成功的邏輯。
尋找問題所在
想要了解這個問題,首先需要了解 interface{} 變量的本質。在 Go 語言中,一個 interface{} 類型的變量包含了2個指針,一個指針指向值的類型,另外一個指針指向實際的值。 我們可以用如下的測試代碼進行驗證。
// InterfaceStructure 定義了一個interface{}的内部結構
type InterfaceStructure struct {
pt uintptr // 到值類型的指針
pv uintptr // 到值内容的指針
}
// asInterfaceStructure 将一個interface{}轉換為InterfaceStructure
func asInterfaceStructure (i interface{}) InterfaceStructure {
return *(*InterfaceStructure)(unsafe.Pointer(&i))
}
func TestInterfaceStructure(t *testing.T) {
var i1, i2 interface{}
var v1 int = 0x0AAAAAAAAAAAAAAA
var v2 int = 0x0BBBBBBBBBBBBBBB
i1 = v1
i2 = v2
fmt.Printf("sizeof interface{} = %d\n", unsafe.Sizeof(i1))
fmt.Printf("i1 %x %+v\n", i1, asInterfaceStructure(i1))
fmt.Printf("i2 %x %+v\n", i2, asInterfaceStructure(i2))
var nilInterface interface{}
fmt.Printf("nil interface = %+v\n", asInterfaceStructure(nilInterface))
}
這段代碼的輸出如下:
sizeof interface{} = 16
i1 aaaaaaaaaaaaaaa {pt:5328736 pv:825741282816}
i2 bbbbbbbbbbbbbbb {pt:5328736 pv:825741282824}
nil interface = {pt:0 pv:0}
是以對于一個 interface{} 類型的 nil 變量來說,它的兩個指針都是 0。這是符合 Go 語言對 nil 的标準定義的。在 Go 語言中,nil 是
零值(Zero Value)
,而在 Java 之類的語言裡,null 實際上是
空指針
。關于零值和空指針有什麼差別,這裡就不再展開了。
當我們将一個具體類型的值指派給一個 interface 類型的變量的時候,就同時把類型和值都指派給了 interface 裡的兩個指針。如果這個具體類型的值是 nil 的話,interface 變量依然會存儲對應的類型指針和值指針。
func TestAssignInterfaceNil(t *testing.T) {
var p *int = nil
var i interface{} = p
fmt.Printf("%v %+v is nil %v\n", i, asInterfaceStructure(i), i == nil)
}
輸入如下:
<nil> {pt:5300576 pv:0} is nil false
可見,在這種情況下,雖然我們把一個 nil 值指派給 interface{},但是實際上 interface 裡依然存了指向類型的指針,是以拿這個 interface 變量去和 nil 常量進行比較的話就會傳回
false
。
如何解決這個問題
想要避開這個 Go 語言的坑,我們要做的就是:
避免将一個有可能為 nil 的具體類型的值指派給 interface 變量。
以上述的
OpenRedis
為例,一種方法是先對
OpenRedis
傳回的結果進行 非nil 檢查,然後再指派給 interface 變量,如下所示。
var storageEngine StorageEngine // 這是一個全局變量
redis := OpenRedis(cfg.Url, dbindex)
if redis != nil {
// 連接配接成功
storageEngine = redis // 确定redis不是nil之後再指派給interface變量
} else {
// 連接配接失敗
...
}
另外一種方法是讓
OpenRedis
函數直接傳回 EntityStorage 接口類型的值,這樣就可以把
OpenRedis
的傳回值直接正确指派給 EntityStorage 接口變量。
// OpenRedis opens redis as entity storage
func OpenRedis(url string, dbindex int) EntityStorage {
c, err := redis.DialURL(url)
if err != nil {
return nil
}
if dbindex >= 0 {
if _, err := c.Do("SELECT", dbindex); err != nil {
return nil
}
}
es := &redisEntityStorage{
c: c,
}
return es
}
至于哪種方法更好,就見仁見智了。希望大家在實際項目中不要踩坑,即使踩了也能快速跳出來!
網友評論
對于此類問題,即多個底層實作全部通過同一個 interface 類型來提供 API 的情況,個人的習慣是,構造函數的傳回類型直接寫成 interface 類型而不是具體的底層實作類型。比如文中的
func OpenRedis(url string, dbindex int) *redisEntityStorage
就可以改寫成
func OpenRedis(url string, dbindex int) EntityStorage
。這樣一來構造函數裡非 nil 的傳回值會被 Go 自動裝箱,傳回 nil 則當作 nil interface value 而不是 nil concrete-typed value 來處理。此外盡量避免 type assertion。
另外,前些天 dave cheney 的一篇文章裡提到了關于 go2 typed nil 的一些設想,非常期待 Go 2 到時候可以把這個坑給填了。
我也覺得interface{}和nil進行比較的時候,應該隻比較值部分就行了,類型部分不管是不是空,都應該算作nil
摘自:http://studygolang.com/articles/10635
轉載于:https://www.cnblogs.com/52php/p/7363101.html