Interface

概念有點像是typescript泛型(但不一樣):讓一個function可以接受不同型別,讓我們可以重複使用code

有兩個type 有各自實作的function

想要用同一個function來print

但不行

type englistBot struct{}
type spanishBot struct{}

func (englishBot) getGreeting() string {
	return "Hello"
}
func (spanishBot) getGreeting() string {
	return "Hola"
}

func printGreeding(eb englishBot) {
	fmt.Println(eb.getGreeting())
}
func printGreeding(sb spanishBot) {
	fmt.Println(sb.getGreeting())
}

可以用interface來解決

Screen Shot 2022-01-06 at 10.05.41 PM.png

可以先定義一個新的type: bot interface

type bot interface {
	getGreeting() string
}

<aside> 💡 此程式內,其他任何的type只要有實作 getGreeting() string,這些type都會自動屬於bot型別(榮譽會員的概念)

</aside>

所以可以把 printGreeting改成type bot

func printGreeding(b bot){
	fmt.Println(b.getGreeting())
}

func main() {
	eb := englishBot{}
	sb := spanishBot{}

	printGreeting(eb)
	printGreeting(sb)
}

因為englishBot與spanishBot都屬於 bot了,所以可以直接使用