Type Switch with Multiple Cases
In Go, a type switch statement can be used to dynamically select a corresponding case based on the type of a value. When multiple types are specified in a single case, an error may be raised if the type of the value does not match any of the listed types.
Consider the following code snippet:
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() } }
When this code is run, it produces the following error:
a.test undefined (type interface {} is interface with no methods)
This error indicates that the type switch did not take effect because the variable a has the type interface{}, which does not have the test() method.
The Go language specification explains that in a type switch statement, when multiple types are specified in a case, the variable declared in that case will have the type of the expression in the type switch guard (in this case, foo). Since foo is of type interface{}, a also becomes an interface{} type.
To resolve this issue and ensure that the test() method can be called, you can explicitly assert that foo has the test() method before performing the type switch, like so:
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() } }
By asserting that foo has the test() method, you can retrieve a value of the appropriate type and call the test() method successfully.
The above is the detailed content of How to Correctly Use Multiple Cases in Go's Type Switch to Avoid Method Errors?. For more information, please follow other related articles on the PHP Chinese website!