interface
interface
什麼是 interface
interface 型別
type Human struct {
name string
age int
phone string
}
type Student struct {
Human //匿名欄位 Human
school string
loan float32
}
type Employee struct {
Human //匿名欄位 Human
company string
money float32
}
//Human 物件實現 Sayhi 方法
func (h *Human) SayHi() {
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}
// Human 物件實現 Sing 方法
func (h *Human) Sing(lyrics string) {
fmt.Println("La la, la la la, la la la la la...", lyrics)
}
//Human 物件實現 Guzzle 方法
func (h *Human) Guzzle(beerStein string) {
fmt.Println("Guzzle Guzzle Guzzle...", beerStein)
}
// Employee 過載 Human 的 Sayhi 方法
func (e *Employee) SayHi() {
fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
e.company, e.phone) //此句可以分成多行
}
//Student 實現 BorrowMoney 方法
func (s *Student) BorrowMoney(amount float32) {
s.loan += amount // (again and again and...)
}
//Employee 實現 SpendSalary 方法
func (e *Employee) SpendSalary(amount float32) {
e.money -= amount // More vodka please!!! Get me through the day!
}
// 定義 interface
type Men interface {
SayHi()
Sing(lyrics string)
Guzzle(beerStein string)
}
type YoungChap interface {
SayHi()
Sing(song string)
BorrowMoney(amount float32)
}
type ElderlyGent interface {
SayHi()
Sing(song string)
SpendSalary(amount float32)
}interface 值
空 interface
interface 函式參數
interface 變數儲存的型別
嵌入 interface
反射
links
Last updated