1. 程式人生 > 其它 >go語言學習——介面

go語言學習——介面

1、介面的定義
import "fmt"

type Personer interface {
    SayHello()
}

type Student struct {

}

func (stu *Student)SayHello()  {
    fmt.Println("老師好")
}

func main()  {
    //建立一個學生物件
    var stu Student
    //通過介面變數的方式來呼叫,必須都實現介面中宣告的所有方法
    var person Personer

    person = &stu
    person.SayHello()
//此時person呼叫的是Student物件中的SayHello方法 } 執行結果: 老師好
2、多型

多型是指同一個介面,使用不同的例項而執行不同的操作

import "fmt"

type Personer interface {
    SayHello()
}

type Student struct {

}

type Teacher struct {

}

func (stu *Student)SayHello()  {
    fmt.Println("老師好")
}

func (stu *Teacher)SayHello()  {
    fmt.Println("學生好
") } func WhoSayHello(p Personer) { p.SayHello() } func main() { var stu Student var tea Teacher WhoSayHello(&stu) WhoSayHello(&tea) } 執行結果: 老師好 學生好