Determining the dynamic type of an interface

suggest change

In 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")
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents