2015-01-06 14 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

方法について_、[OK]:=インターフェース{}(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の変数に割り当てていますが、変数名は_なので無視されます。 MyTypeSometherを実装

場合、それは何もコンパイルしないとどうなる

+0

説明ありがとうございます! –

+0

右手に 'MyType'の*ポインタ*があるので、黒い識別子が' * Somether'である必要はありません。まだ勉強してる。 :-) –

+0

あなたはコンテナのようなインタフェースの値を考えることができます。正しいメソッドを実装している限り、その中に必要なものを置くことができます。 構造体へのポインタまたは構造体を直接含めることができます。 経験則として、インタフェース値へのポインタを作る必要はありません –

関連する問題