詳解Golang語(yǔ)言中的interface
interface是一組method簽名的組合,interface可以被任意對(duì)象實(shí)現(xiàn),一個(gè)對(duì)象也可以實(shí)現(xiàn)多個(gè)interface。任意類型都實(shí)現(xiàn)了空interface(也就是包含0個(gè)method的interface),空interface可以存儲(chǔ)任意類型的值。interface定義了一組方法,如果某個(gè)對(duì)象實(shí)現(xiàn)了某個(gè)接口的所有方法,則此對(duì)象就實(shí)現(xiàn)了此接口。
go version go1.12
package main
import (
"fmt"
)
// 定義struct
type Human struct {
name string
age int
phone string
}
type Student struct {
Human // 匿名字段
school string
loan float32
}
type Employee struct {
Human // 匿名字段
company string
money float32
}
// Human對(duì)象實(shí)現(xiàn)SayHi()方法
func (h Human) SayHi() {
fmt.Printf("Hi, I am %s, you can call me on %s\n", h.name, h.phone)
}
// Human對(duì)象實(shí)現(xiàn)Sing()方法
func (h Human) Sing(lyrics string) {
fmt.Println("La la la...", lyrics)
}
// Human對(duì)象實(shí)現(xiàn)Guzzle()方法
func (h Human) Guzzle(beerStein string) {
fmt.Println("Guzzle Guzzle Guzzle...", beerStein)
}
// Employee對(duì)象重寫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對(duì)象實(shí)現(xiàn)BorrowMoney()方法
func (s Student) BorrowMoney(amount float32) {
s.loan += amount
}
// Employee對(duì)象實(shí)現(xiàn)SpendSalary()方法
func (e Employee) SpendSalary(amount float32) {
e.money -= amount
}
// 定義interface,interface是一組method簽名的組合
// interface可以被任意對(duì)象實(shí)現(xiàn),一個(gè)對(duì)象也可以實(shí)現(xiàn)多個(gè)interface
// 任意類型都實(shí)現(xiàn)了空interface(也就是包含0個(gè)method的interface)
// 空interface可以存儲(chǔ)任意類型的值
// interface Men的3個(gè)method被Human,Student,Employee實(shí)現(xiàn),也就是這3個(gè)對(duì)象都實(shí)現(xiàn)了interface Men。即:
// interface定義了一組方法,如果某個(gè)對(duì)象實(shí)現(xiàn)了某個(gè)接口的所有方法,則此對(duì)象就實(shí)現(xiàn)了此接口。
type Men interface {
SayHi()
Sing(lyrice string)
Guzzle(beerStein string)
}
// interface YoungChap的BorrowMoney() method只被Student對(duì)象實(shí)現(xiàn),也就是只有Student實(shí)現(xiàn)了YoungChap
type YoungChap interface {
SayHi()
Sing(song string)
BorrowMoney(amount float32)
}
// interface ElderlyGent的SpendSalary() method只被Employee對(duì)象實(shí)現(xiàn),也就是只有Employee實(shí)現(xiàn)了ElderlyGent
type ElderlyGent interface {
SayHi()
Sing(song string)
SpendSalary(amount float32)
}
func main() {
// 定義Student類型的變量
lucy := Student{Human{"lucy", 19, "10086"}, "tsinghua", 100.00}
lily := Student{Human{"lily", 19, "10086"}, "tsinghua", 100.00}
liming := Student{Human{"liming", 19, "10086"}, "tsinghua", 100.00}
// 定義Employee類型的變量
tom := Employee{Human{"tom", 29, "10000"}, "Google", 200.00}
// 定義Men類型的變量i
var i Men
// i存儲(chǔ)Student
i = lucy
fmt.Println("This is lucy, a student:")
i.SayHi()
i.Sing("Happy Birthday")
i.Guzzle("Ha ha ha...")
// i存儲(chǔ)Employee
i = tom
fmt.Println("This is tom, an Employee:")
i.SayHi()
// 定義slice Men,包含Men類型元素的切片,這個(gè)slice可以被賦予實(shí)現(xiàn)了Men接口的任意結(jié)構(gòu)的對(duì)象
fmt.Println("Let's use a slice of Men and see what happens:")
x := make([]Men, 3)
// 三個(gè)不同類型(不同Method)的元素,實(shí)現(xiàn)了同一個(gè)interface(Men)
x[0], x[1], x[2] = lucy, lily, liming
for _, value := range x {
value.SayHi()
}
}
函數(shù)參數(shù)
interface接口還可以作為函數(shù)參數(shù),因?yàn)閕nterface的變量可以持有任意實(shí)現(xiàn)該interface類型的對(duì)象,我們可以通過(guò)定義interface參數(shù),讓函數(shù)接受各種類型的參數(shù)。 判斷interface變量存儲(chǔ)的元素的類型,目前常用的有兩種方法:Comma-ok斷言和switch測(cè)試。
go version go1.12
/**
* interface接口作為函數(shù)參數(shù)
* 判斷interface變量存儲(chǔ)的元素的類型
*/
package main
import (
"fmt"
"strconv"
)
// 定義Human對(duì)象
type Human struct {
name string
age int
phone string
}
// 定義空接口
type Element interface{}
// 定義切片
type List []Element
// 定義Person對(duì)象
type Person struct {
name string
age int
}
// 通過(guò)定義interface參數(shù),讓函數(shù)接受各種類型的參數(shù)
// 通過(guò)這個(gè)Method(方法),Human對(duì)象實(shí)現(xiàn)了fmt.Stringer接口
// Stringer接口是fmt.Println()的參數(shù),最終使得Human對(duì)象可以作為fmt.Println的參數(shù)被調(diào)用
func (h Human) String() string {
return "<" + h.name + " - " + strconv.Itoa(h.age) + " years - phone: " + h.phone + ">"
}
// 通過(guò)定義interface參數(shù),讓函數(shù)接受各種類型的參數(shù)
// 通過(guò)這個(gè)Method(方法),Person對(duì)象實(shí)現(xiàn)了fmt.Stringer接口
// Stringer接口是fmt.Println()的參數(shù),最終使得Person對(duì)象可以作為fmt.Println的參數(shù)被調(diào)用
func (p Person) String() string {
return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)"
}
func main() {
// interface作為函數(shù)的參數(shù)傳遞
Lucy := Human{"Lucy", 29, "10086"}
fmt.Println("This human is:", Lucy)
list := make(List, 3)
list[0] = 100
list[1] = "Hello Golang!"
list[2] = Person{"Lily", 19}
// Comma-ok斷言
for index, element := range list {
// 判斷變量的類型 格式:value, ok = element(T)
// value是interface變量的值,ok是bool類型,element是interface的變量,T是斷言的interface變量的類型
if value, ok := element.(int); ok {
fmt.Printf("list[%d] is an int and it's value is %d\n", index, value)
} else if value, ok := element.(string); ok {
fmt.Printf("list[%d] is a string and it's value is %s\n", index, value)
} else if value, ok := element.(Person); ok {
fmt.Printf("list[%d] is a Person and it's value is %s\n", index, value)
} else {
fmt.Printf("list[%d] is a different type\n", index)
}
}
// switch
for index, element := range list {
// 注意:element.(type)語(yǔ)法不能在switch外的任何邏輯中使用
switch value := element.(type) {
case int:
fmt.Printf("list[%d] is an int, it's value is %d\n", index, value)
case string:
fmt.Printf("list[%d] is a string, it's value is %s\n", index, value)
case Person:
fmt.Printf("list[%d] is a Person, it's value is %s\n", index, value)
default:
fmt.Printf("list[%d] is a differernt type", index)
}
}
}
以上就是詳解Golang語(yǔ)言中的interface的詳細(xì)內(nèi)容,更多關(guān)于Golang語(yǔ)言中的interface的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
golang開(kāi)發(fā)go包依賴管理godep使用教程
這篇文章主要為大家介紹了golang開(kāi)發(fā)go包依賴管理godep使用教程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11
Golang中數(shù)據(jù)結(jié)構(gòu)Queue的實(shí)現(xiàn)方法詳解
這篇文章主要給大家介紹了關(guān)于Golang中數(shù)據(jù)結(jié)構(gòu)Queue的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09
Go?語(yǔ)言進(jìn)階freecache源碼學(xué)習(xí)教程
這篇文章主要為大家介紹了Go?語(yǔ)言進(jìn)階freecache源碼學(xué)習(xí)教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
詳細(xì)介紹Go語(yǔ)言之?dāng)?shù)組與切片
這篇文章介紹Go語(yǔ)言之?dāng)?shù)組與切片,數(shù)組是具有相同唯一類型的一組已編號(hào)且長(zhǎng)度固定的數(shù)據(jù)項(xiàng)序列,這種類型可是任意的原始類型如整形、字符串或自定義類型。切片是數(shù)組的一個(gè)引用,因此切片是引用類型,在進(jìn)行傳遞時(shí),遵守引用傳遞的機(jī)制,下面我們就來(lái)詳細(xì)了解一下該內(nèi)容2021-10-10

