While learning about the type switch statement in Go, I tried to check for the "struct" type as follows:
package main
import "fmt"
func moo(i interface{}) {
switch v := i.(type) {
case string:
fmt.Printf("Byte length of %T: %v
", v, len(v))
case int:
fmt.Printf("Two times this %T: %v
", v, v)
case bool:
fmt.Printf("Truthy guy is %v
", v)
case struct:
fmt.Printf("Life is complicated with %v
", v)
default:
fmt.Println("don't know")
}
}
func main() {
moo(21)
moo("hello")
moo(true)
}
However, this resulted in a syntax error related to the struct
type (not seen if the case statement checking for the struct
type is removed:
tmp/sandbox396439025/main.go:13: syntax error: unexpected :, expecting {
tmp/sandbox396439025/main.go:14: syntax error: unexpected (, expecting semicolon, newline, or }
tmp/sandbox396439025/main.go:17: syntax error: unexpected semicolon or newline, expecting :
tmp/sandbox396439025/main.go:20: syntax error: unexpected main, expecting (
tmp/sandbox396439025/main.go:21: syntax error: unexpected moo
Is there a reason why the struct
type cannot be checked for here? Note that the func moo()
is checking for i
of type interface{}
, an empty interface which should supposedly be implemented by every type, including struct
Go Playground full code: