golang中的接口实现(一)

golang中的接口实现

// 定义一个接口
type People interface {
    getAge() int // 定义抽象方法1
    getName() string // 定义抽象方法2
}

type Man struct {
}

func (a *Man) getAge() int { // 实现抽象方法1
    return 18
}

func (a *Main) getName() string { // 实现抽象方法2
    return "Sheldon"
}

func TestPeople(p interface{}) {
    switch p.(type) { // 变量.(type) 只能在 switch 中使用
        case People:
            fmt.Println("实现了 People 接口")
        case People2:
            fmt.Println("实现了 People2 接口")
    }
}

func main() {
    man1 := Man{}
    TestPeople(man1)
}


posted on 2019-04-10 17:54  Sweet小马  阅读(4415)  评论(0编辑  收藏  举报

导航