詳解Golang語(yǔ)言中的interface
interface是一組method簽名的組合,interface可以被任意對(duì)象實(shí)現(xiàn),一個(gè)對(duì)象也可以實(shí)現(xiàn)多個(gè)interface。任意類(lèi)型都實(shí)現(xiàn)了空interface(也就是包含0個(gè)method的interface),空interface可以存儲(chǔ)任意類(lèi)型的值。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ì)象重寫(xiě)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
// 任意類(lèi)型都實(shí)現(xiàn)了空interface(也就是包含0個(gè)method的interface)
// 空interface可以存儲(chǔ)任意類(lèi)型的值
// 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類(lèi)型的變量
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類(lèi)型的變量
tom := Employee{Human{"tom", 29, "10000"}, "Google", 200.00}
// 定義Men類(lèi)型的變量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類(lèi)型元素的切片,這個(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è)不同類(lèi)型(不同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類(lèi)型的對(duì)象,我們可以通過(guò)定義interface參數(shù),讓函數(shù)接受各種類(lèi)型的參數(shù)。 判斷interface變量存儲(chǔ)的元素的類(lèi)型,目前常用的有兩種方法:Comma-ok斷言和switch測(cè)試。
go version go1.12
/**
* interface接口作為函數(shù)參數(shù)
* 判斷interface變量存儲(chǔ)的元素的類(lèi)型
*/
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ù)接受各種類(lèi)型的參數(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ù)接受各種類(lèi)型的參數(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 {
// 判斷變量的類(lèi)型 格式:value, ok = element(T)
// value是interface變量的值,ok是bool類(lèi)型,element是interface的變量,T是斷言的interface變量的類(lèi)型
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)文章
使用IDEA配置GO語(yǔ)言的開(kāi)發(fā)環(huán)境備忘錄
最近在配置idea開(kāi)發(fā)go語(yǔ)言時(shí)碰到很多問(wèn)題,想著很多人都可能會(huì)遇到,所以下面這篇文章主要給大家介紹了關(guān)于使用IDEA配置GO語(yǔ)言的開(kāi)發(fā)環(huán)境,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2024-05-05
Golang連接PostgreSQL基本操作的實(shí)現(xiàn)
PostgreSQL是常見(jiàn)的免費(fèi)的大型關(guān)系型數(shù)據(jù)庫(kù),本文主要介紹了Golang連接PostgreSQL基本操作的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02
詳解Go?語(yǔ)言如何通過(guò)測(cè)試保證質(zhì)量
這篇文章主要為大家介紹了Go?語(yǔ)言如何通過(guò)測(cè)試保證質(zhì)量詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
關(guān)于Gin框架中的Cookie和Session的使用方法
為了實(shí)現(xiàn)跨請(qǐng)求的數(shù)據(jù)共享,我們可以使用Cookie和Session,本文將結(jié)合實(shí)際案例,詳細(xì)介紹在Go語(yǔ)言的Gin框架中如何使用Cookie和Session,并通過(guò)代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2024-10-10
使用Go?goroutine實(shí)現(xiàn)并發(fā)的Clock服務(wù)
這篇文章主要為大家詳細(xì)介紹了如何使用Go?goroutine實(shí)現(xiàn)并發(fā)的Clock服務(wù),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-06-06
golang使用iconv報(bào)undefined:XXX的問(wèn)題處理方案
這篇文章主要介紹了golang使用iconv報(bào)undefined:XXX的問(wèn)題處理方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03

