go語言中的interface使用執行個體_Golang

來源:互聯網
上載者:User

go語言中的interface是一組未實現的方法的集合,如果某個對象實現了介面中的所有方法,那麼此對象就實現了此介面。與其它物件導向語言不同的是,go中無需顯示聲明調用了哪個介面。

複製代碼 代碼如下:

package main
 
import (
 "fmt"
)
 
type I interface {
 Get() int
 Put(int)
}
 
type S struct{ i int }
 
func (p *S) Get() int  { return p.i }
func (p *S) Put(v int) { p.i = v }
 
type R struct{ i int }
 
func (p *R) Get() int  { return p.i }
func (p *R) Put(v int) { p.i = v }
 
func f1(p I) {
 fmt.Println(p.Get())
 p.Put(1)
}
 
//interface{}空介面,能接受任何類型。.(I)是類型斷言,用於轉換something到I類型的介面
func f2(p interface{}) {
 if t, ok := p.(S); ok {
  fmt.Println("S:", t)
 } else if t, ok := p.(I); ok {
  fmt.Println("I:", t.Get())
 }
}
 
func f3(p interface{}) {
 switch t := p.(type) {
 case S:
  fmt.Println("S:", t.Get())
 case R:
  fmt.Println("R:", t.Get())
 case I:
  fmt.Println("I:", t.Get())
 default:
  fmt.Println("unknow type")
 }
}
 
func main() {
 s := S{101}
 
 f1(&s)
 f2(&s)
 
 r := R{1111}
 f3(&r)
}

如上結構S實現了I的兩個方法,因此S實現了I。因為S實現了I,因此可以調用f向其傳遞S類型值得指標。
 
總結如下:
(1)使用“comma, ok” 來判斷一個介面類型是否實現了某個特定介面:

複製代碼 代碼如下:

if t, ok := something.(I) ; ok {
// 對於某些實現了介面I 的
// t 是其所擁有的類型
}

(2)聲明為 interface 類型的變數,可以儲存任何實現了 interface 中所有方法的類型的變數
(3)空介面可代表任何類型,可做形參和傳回型別

複製代碼 代碼如下:

package main
 
import "fmt"
 
func main() {
 //interface{}
 var i interface{} = 100
 var s interface{} = "hello"
 fmt.Printf("i = %d, s = %s\n", i, s)
 s = i
 fmt.Printf("i = %d, s = %d\n", i, s)
}

(4)interface組合

將一個 interface1 嵌入到另一個 interface2 的聲明中,其作用相當於把 interface1 的函數包含到 interface2 中,但是組合中不同有重複的方法

  註:
  a. 只要兩個介面中的方法列表相同(與順序無關),即為相同的介面,可以相互賦值
  b. interface1 的方法列表屬於另一個 interface2 的方法列表的子集,interface2 可以賦值給 interface1,反之不成立(因為方法缺失),interface2 中的方法會覆蓋 interface1 中同名的方法
  c. 可以嵌入包中的 interface

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.