Go 語言編程 — 高級數據類型 — 接口

目錄

文章目錄

接口

接口是 Golang 提供的一種數據類型,使用 type 和 interface 關鍵字來聲明。接口可以把所有的具有共性的方法(Method)集合在一起,任何其他類型只要實現了這些方法就是實現了這個接口。

格式:

/* 定義接口 */
type interface_name interface {
   method_name1 [return_type]
   method_name2 [return_type]
   method_name3 [return_type]
   ...
   method_namen [return_type]
}

/* 定義結構體 */
type struct_name struct {
   /* variables */
}

/* 實現接口方法 */
func (struct_name_variable struct_name) method_name1() [return_type] {
   /* 方法實現 */
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
   /* 方法實現*/
}

示例:定義了一個接口 Phone,在這個接口裏面有一個方法 call()。然後我們在 main 函數裏面定義了一個 Phone(接口)類型變量,並分別爲之賦值爲 NokiaPhone 和 IPhone,然後調用 call() 方法。

package main

import "fmt"

type Phone interface {
    call()
}

type NokiaPhone struct {
}

func (nokiaPhone NokiaPhone) call() {
    fmt.Println("I am Nokia, I can call you!")
}

type IPhone struct {
}

func (iPhone IPhone) call() {
    fmt.Println("I am iPhone, I can call you!")
}

func main() {
    var phone Phone

    phone = new(NokiaPhone)
    phone.call()

    phone = new(IPhone)
    phone.call()
}

結果:

I am Nokia, I can call you!
I am iPhone, I can call you!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章