Type Switch with Multiple Cases in Go
When using a type switch with multiple cases, one may encounter an error stating that a variable in a case with multiple types is undefined. This behavior stems from the Go language specification, which dictates that a type switch guard may include a short variable declaration.
In such cases, the variable has the same type as the type listed in single-type cases. However, in cases with a listing of multiple types, the variable has the type of the expression in the type switch guard.
To illustrate this, consider the following code:
type A struct { a int } func (this *A) test() { fmt.Println(this) } type B struct { A } var foo interface{} foo = A{} switch a := foo.(type) { case B, A: a.test() }
Running this code will result in the error "a.test undefined (type interface {} is interface with no methods)." This is because the variable a has the type interface{}, not the type of the specific case.
To resolve this issue, one can assert that the type switch guard expression has the expected method. For instance:
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() } }
This code first checks if foo has the test() method, and if it does, it assigns the value of foo to a and calls the test() method.
The above is the detailed content of Why Does a Type Switch with Multiple Cases in Go Cause 'undefined' Variable Errors, and How Can This Be Resolved?. For more information, please follow other related articles on the PHP Chinese website!