速戰速決 go https://github.com/webabcd/GoSample
作者 webabcd
速戰速決 go - go 面向對象: 接口(接口的定義,接口的實現,接口的使用)
示例如下:
oop/interface1.go
// go 面向對象 - 接口(接口的定義,接口的實現,接口的使用)
package oop
import "fmt"
func Interface1Sample() {
// 結構體實現接口的示例
interface1_sample1()
// 函數實現接口的示例(這個不常用)
interface1_sample2()
}
func interface1_sample1() {
// 聲明一個 interface11 類型的變量,初始化的結構體必須要實現 interface11 接口
var a interface11 = new(interface1_struct1)
// 聲明一個 interface12 類型的變量,初始化的結構體必須要實現 interface12 接口
var b interface12 = new(interface1_struct1)
// 聲明一個 interface13 類型的變量,初始化的結構體必須要實現 interface13 接口(即必須同時實現 interface11 接口和 interface12 接口)
var c interface13 = new(interface1_struct1)
// 調用你實現的接口的方法
a.hello("webabcd") // hello: webabcd
b.hi("webabcd") // hi: webabcd
c.hello("webabcd") // hello: webabcd
c.hi("webabcd") // hi: webabcd
// 接口作爲參數傳遞
interface1_func1(nil)
interface1_func1(new(interface1_struct1))
}
func interface1_func1(a interface12) {
if a == nil {
fmt.Println("參數 a 爲 nil") // 參數 a 爲 nil
} else {
a.hi("webabcd") // hi: webabcd
}
}
// 定義一個接口
type interface11 interface {
hello(name string)
}
type interface12 interface {
hi(name string)
}
type interface13 interface {
// 內嵌接口
// 內嵌接口可以實現類似繼承的效果,這裏相當於 interface13 繼承了 interface11 和 interface12
interface11
interface12
}
// 定義一個結構體(後續會爲這個結構體實現 interface11 接口,interface12 接口,interface13 接口)
type interface1_struct1 struct {
}
// 實現 interface11 接口的方法
func (s *interface1_struct1) hello(name string) {
fmt.Println("hello: " + name)
}
// 實現 interface12 接口的方法
func (s *interface1_struct1) hi(name string) {
fmt.Println("hi: " + name)
}
func interface1_sample2() {
// 函數實現接口的示例
var b interface11 = myfunc(interface1_func2)
b.hello("webabcd") // hello: webabcd
// 匿名函數實現接口的示例
var a interface11 = myfunc(func(name string) {
fmt.Println("hello: " + name)
})
a.hello("webabcd") // hello: webabcd
}
func interface1_func2(name string) {
fmt.Println("hello: " + name) // hello: webabcd
}
// 爲函數定義一個自定義類型(如果需要讓函數實現接口,那麼就需要通過自定義類型來實現)
type myfunc func(string)
// 爲自定義類型實現 interface11 接口的方法
func (f myfunc) hello(name string) {
// 調用函數
f(name)
}
速戰速決 go https://github.com/webabcd/GoSample
作者 webabcd