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



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM