Go語言基礎(chǔ)go接口用法示例詳解
概述
Go 語言中的接口就是方法簽名的集合,接口只有聲明,沒有實現(xiàn),不包含變量。
語法
定義接口
type [接口名] interface { 方法名1(參數(shù)列表) 返回值列表 方法名2(參數(shù)列表) 返回值列表 ... }
例子
type Isay interface{ sayHi() }
實現(xiàn)接口
例子
//定義接口的實現(xiàn)類 type Chinese struct{} //實現(xiàn)接口 func (_ *Chinese) sayHi() { fmt.Println("中國人說嗨") }
//中國人 type Chinese struct{} //美國人 type Americans struct{} func (this *Chinese) sayHi() { fmt.Println("中國人說嗨") } func (this Americans) sayHi() { fmt.Println("美國人說hi") } //調(diào)用 &Chinese{}.sayHi() Americans{}.sayHi()
空接口
在Go語言中,所有其它數(shù)據(jù)類型都實現(xiàn)了空接口。
interface{}
var v1 interface{} = 1 var v2 interface{} = "abc" var v3 interface{} = struct{ X int }{1}
如果函數(shù)打算接收任何數(shù)據(jù)類型,則可以將參考聲明為interface{}。最典型的例子就是標(biāo)準(zhǔn)庫fmt包中的Print和Fprint系列的函數(shù):
func Fprint(w io.Writer, a ...interface{}) (n int, err error) func Fprintf(w io.Writer, format string, a ...interface{}) func Fprintln(w io.Writer, a ...interface{}) func Print(a ...interface{}) (n int, err error) func Printf(format string, a ...interface{}) func Println(a ...interface{}) (n int, err error)
接口的組合
一個接口中包含一個或多個接口
//說話 type Isay interface{ sayHi() } //工作 type Iwork interface{ work() } //定義一個接口,組合了上述兩個接口 type IPersion interface{ Isay Iwork } type Chinese struct{} func (_ Chinese) sayHi() { fmt.Println("中國人說中國話") } func (_ Chinese) work() { fmt.Println("中國人在田里工作") } //上述接口等價于: type IPersion2 interface { sayHi() work() }
總結(jié)
interface類型默認是一個指針使用空接口可以保存任意值不能比較空接口中的動態(tài)值定義了一個接口,這些方法必須都被實現(xiàn),這樣編譯并使用
示例
package main import "fmt" //中國話 type Isay interface { sayHi() } //工作 type Iwork interface { work() } //中國人 type Chinese struct{} //美國人 type Americans struct{} func (this *Chinese) sayHi() { fmt.Println("中國人說嗨") } func (this Americans) sayHi() { fmt.Println("美國人說hi") } type IPersion interface { Isay Iwork } func (_ Chinese) work() { fmt.Println("中國人在田里工作") } func main() { var chinese Isay = &Chinese{} chinese.sayHi() Americans{}.sayHi() //接口組合 var ipersion IPersion = &Chinese{} ipersion.sayHi() ipersion.work() }
以上就是Go語言基礎(chǔ)go接口用法示例詳解的詳細內(nèi)容,更多關(guān)于Go 語言基礎(chǔ)的資料請關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。