go語言學習——介面
阿新 • • 發佈:2022-04-18
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方法 } 執行結果: 老師好
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) } 執行結果: 老師好 學生好