2015-01-06 58 views
8

我讀過「Effective Go」和其他Q &就像這樣:golang interface compliance compile type check,但是我無法正確理解如何使用這種技術。檢查值是否實現接口的說明。 Golang

請參見例如:

type Somether interface { 
    Method() bool 
} 

type MyType string 

func (mt MyType) Method2() bool { 
    return true 
} 

func main() { 
    val := MyType("hello") 

    //here I want to get bool if my value implements Somether 
    _, ok := val.(Somether) 
    //but val must be interface, hm..what if I want explicit type? 

    //yes, here is another method: 
    var _ Iface = (*MyType)(nil) 
    //but it throws compile error 
    //it would be great if someone explain the notation above, looks weird 
} 

有沒有簡單的方法(例如,不使用反射)校驗值,如果它實現了一個接口?

+1

怎麼樣_,確定:=接口{}(VAL)(Somether)。? – c0ming

回答

14

如果您不知道值的類型,則只需檢查值是否實現接口。 如果類型已知,則該檢查由編譯器自動完成。

如果你真的想反正檢查,你可以用你給的第二種方法做到這一點:這將錯誤在編譯時

var _ Somether = (*MyType)(nil) 

prog.go:23: cannot use (*MyType)(nil) (type *MyType) as type Somether in assignment: 
    *MyType does not implement Somether (missing Method method) 
[process exited with non-zero status] 

,你在這裏做什麼,將MyType類型(和nil值)的指針分配給類型爲Somether的變量,但由於變量名稱是_,因此忽略它。

如果MyType實施Somether,它會編譯和什麼也不做

+0

感謝您的解釋! –

+0

爲什麼黑色標識符不一定需要是'* Somether',因爲右手有一個指向MyType的指針?我還在學習。 :-) –

+0

你可以想象一個像容器這樣的接口值,只要它實現了正確的方法,你就可以放入任何你想要的東西。它可以直接包含一個指向結構體或結構體的指針。作爲一個經驗法則,你永遠不需要製作一個指向接口值的指針 –