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


相关文章:

  • 2021-07-07
  • 2022-12-23
  • 2022-02-12
  • 2022-12-23
  • 2021-10-03
  • 2022-02-27
  • 2021-08-03
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2023-04-03
  • 2023-03-20
  • 2022-12-23
  • 2021-09-03
相关资源
相似解决方案