Go FAQ: The Pipe Operator In Generics Is Not A Sum Type
An increasingly-frequently asked question in the Go subreddit is some variant of: “I have this code but it isn’t doing what I expect it to do.”
type MyStruct struct {
// definition
}
type OtherStruct struct {
// definition
}
type MySumType interface {
MyStruct | OtherStruct
}
func main() {
myStruct := MyStruct{...}
printVal(myStruct)
}
func printVal[T MySumType](in T) {
switch val := in.(type) {
case MyStruct:
fmt.Println("It's a MyStruct")
case OtherStruct:
fmt.Println("It's an OtherStruct")
}
}There’s a variety of manifestations of the question at this point,
such as, “the switch won’t compile” or “I can’t take a MySumType as a
type parameter on a function”, or a couple of other varients, but the
specific variant doesn’t matter because there is no syntax tweak to
fix this, because this is not what the | operator is.