從介面確定底層型別

在 go 中,有時知道你已經傳遞了哪種基礎型別。這可以通過型別開關完成。這假設我們有兩個結構:

type Rembrandt struct{}

func (r Rembrandt) Paint() {}

type Picasso struct{}

func (r Picasso) Paint() {}

實現 Painter 介面:

type Painter interface {
    Paint()
}

然後我們可以使用此開關來確定基礎型別:

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