Go Interfaces Determining underlying type from interface

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

In go it can sometimes be useful to know which underlying type you have been passed. This can be done with a type switch. This assumes we have 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 we can use this switch to determine the underlying type:

func WhichPainter(painter Painter) {
    switch painter.(type) {
    case Rembrandt:
        fmt.Println("The underlying type is Rembrandt")
    case Picasso:
        fmt.Println("The underlying type is Picasso")
    default:
        fmt.Println("Unknown type")
    }
}


Got any Go Question?