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() } }
source share