# Go 語言接口
Go 語言提供了另外一種數據類型即接口,它把所有的具有共性的方法定義在一起,任何其他類型只要實現了這些方法就是實現了這個接口。
### 實例
```
/* 定義接口 */
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] {
/* 方法實現*/
}
```
### 實例
```
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()
}
```
在上面的例子中,我們定義了一個接口Phone,接口里面有一個方法call()。然后我們在main函數里面定義了一個Phone類型變量,并分別為之賦值為NokiaPhone和IPhone。然后調用call()方法,輸出結果如下:
```
I am Nokia, I can call you!
I am iPhone, I can call you!
```
- Go 語言簡介
- Go 語言環境安裝
- Go 語言結構
- Go 語言基礎語法
- Go 語言數據類型
- Go 語言變量
- Go 語言常量
- Go 語言運算符
- Go 語言條件語句
- Go 語言 if 語句
- Go 語言 if...else 語句
- Go 語言 if 語句嵌套
- Go 語言 switch 語句
- Go 語言 select 語句
- Go 語言循環語句
- Go 語言 for 循環
- Go 語言循環嵌套
- Go 語言 break 語句
- Go 語言 continue 語句
- Go 語言 goto 語句
- Go 語言函數
- Go 語言函數值傳遞值
- Go 語言函數引用傳遞值
- Go 語言函數作為值
- Go 語言函數閉包
- Go 語言函數方法
- Go 語言變量作用域
- Go 語言數組
- Go 語言多維數組
- Go 語言向函數傳遞數組
- Go 語言指針
- Go 語言指針數組
- Go 語言指向指針的指針
- Go 語言指針作為函數參數
- Go 語言結構體
- Go 語言切片(Slice)
- Go 語言范圍(Range)
- Go 語言Map(集合)
- Go 語言遞歸函數
- Go 語言類型轉換
- Go 語言接口
- Go 錯誤處理
- Go 語言開發工具