Golang few cases in type switch

when i run the code snippet below it causes an error

a.test undefined (interface of type {} - interface without methods)

It seems that the type switch is not taking effect.

package main import ( "fmt" ) type A struct { a int } func(this *A) test(){ fmt.Println(this) } type B struct { A } func main() { var foo interface{} foo = A{} switch a := foo.(type){ case B, A: a.test() } } 

If I change it to

  switch a := foo.(type){ case A: a.test() } 

Now this is normal.

+6
source share
1 answer

This is normal behavior, which is determined by the specification (emphasis mine):

TypeSwitchGuard may include a short variable declaration. When this form is used, the variable is declared at the beginning of the implicit block in each sentence. In articles with a listing listing only one type, a variable has that type; otherwise, the variable has an expression type in TypeSwitchGuard .

So, actually the type switch takes effect, but the variable a retains the type interface{} .

One way you can get around this is to assert that foo has a test() method that will look something like this:

 package main import ( "fmt" ) type A struct { a int } func (this *A) test() { fmt.Println(this) } type B struct { A } type tester interface { test() } func main() { var foo interface{} foo = &B{} if a, ok := foo.(tester); ok { fmt.Println("foo has test() method") a.test() } } 
+3
source

Source: https://habr.com/ru/post/1012284/


All Articles