Multiple Cases in Go Type Switches
When assigning an interface value to a type-switched variable, the resulting type depends on the case list structure. Multiple case listings in a switch-case statement may cause unexpected behavior.
In the code snippet you provided:
switch a := foo.(type){ case B, A: a.test() }
The error arises because the type of the variable a is interface{}, not A or B. This is because the case list contains multiple types, so the type of a remains the same as the type of the interface expression (foo).
To resolve this, the case list should contain only a single type:
switch a := foo.(type){ case A: a.test() }
By limiting the case list to a specific type, the variable a will have the expected type, allowing the method call to succeed.
Alternatively, you can explicitly assert the interface type using an assertion expression:
if a, ok := foo.(tester); ok { fmt.Println("foo has test() method") a.test() }
In this case, the variable a will only have the expected type if the assertion is successful (i.e., ok is true).
The above is the detailed content of How Can Multiple Cases in Go Type Switches Lead to Unexpected Behavior?. For more information, please follow other related articles on the PHP Chinese website!