Explanation to check if the value implements the interface

I read the Effective Move and other questions and answers: checking for golang compatibility type compliance , but nonetheless, I cannot correctly understand how to use this technique.

Please see an example:

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 } 

Are there any simple ways (for example, without using reflection) to check the value if it implements the interface?

+19
type-conversion interface go
source share
2 answers

You only need to check if the value implements the interface if you do not know the type of value. If the type is known, this check is automatically performed by the compiler.

If you really want to check anyways, you can do it with the second method that you specified:

 var _ Somether = (*MyType)(nil) 

which will be a compile time error:

 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] 

What are you doing here assigns a pointer of type MyType (and nil value) to a variable of type Somether , but since the variable name is _ , it is ignored.

If MyType implemented by Somether , it will compile and do nothing

+26
source share

The following will work:

 val:=MyType("hello") var i interface{}=val v, ok:=i.(Somether) 
0
source share

All Articles