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:
struct
is not a type, it's a keyword.
This is a type for example (given using a type literal):
struct { i int }
Or Point
:
type Point struct { X, Y int }
So the following code works:
switch v := i.(type) {
case struct{ i int }:
fmt.Printf("Life is complicated with %v
", v)
case Point:
fmt.Printf("Point, X = %d, Y = %d
", v.X, v.Y)
}
You may look at struct
as being a kind of type, which you can check using reflection, for example:
var p Point
if reflect.TypeOf(p).Kind() == reflect.Struct {
fmt.Println("It's a struct")
}
Try it on the Go Playground.