Determining the dynamic type of an interface
suggest changeIn Go it can be useful to know the dynamic type of an interface value. A type switch does that. In the spec, "underlying type" means something else (the type left after removing names), so this page says dynamic type. This example assumes two structs:
type Rembrandt struct{}
func (r Rembrandt) Paint() {}
type Picasso struct{}
func (r Picasso) Paint() {}
That implement the Painter interface:
type Painter interface {
Paint()
}
Then this switch reports the dynamic type:
func WhichPainter(painter Painter) {
switch painter.(type) {
case Rembrandt:
fmt.Println("The dynamic type is Rembrandt")
case Picasso:
fmt.Println("The dynamic type is Picasso")
default:
fmt.Println("Unknown type")
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents