原文鏈接:https://www.zhoubotong.site/post/86.html
這里介紹下介面interface嵌套的用法,大家知道Go語言中不僅僅結構體與結構體之間可以嵌套,介面與介面之間也可以嵌套,通過介面的嵌套我們可以定義出新的介面,
Golang 的介面嵌套,其實也就是一個介面里面包含一個或多個其他的介面,被包含的介面的所有方法都會被包含到新的介面中,
只有實作介面中所有的方法,包括被包含的介面的方法,才算是實作了介面,
Go語言介面嵌套
語法
type Interface1 interface{
func1()
}
type Interface2 interface{
func2()
}
type Interface interface{
Interface1
Interface2
func()
}
說明
上面我們定義了一個介面 Interface1 和一個介面 Interface2,介面 Interface1 里面由一個方法 func1,介面 Interface12 里面有一個函式 func2,
接著我們定義了介面 Interface,介面 Interface 里面包含了介面 Interface1 和介面 Interface2,同時包含了方法 func,
此時介面 Interface 相當于包含了方法 func1、func2 和 func,所以我們必須實作 func1、func2 和 func 這三個方法才算實作了介面 Interface,
例子
介面嵌套
必須實作嵌套的介面的所有方法,才算實作介面
package main
import (
"fmt"
)
type Studenter struct { // 該Studenter結構體用來演示 如何實作介面的所有的方法
}
type Reader interface {
ReaderFunc()
}
type Writer interface {
WriterFunc(str string)
}
type ReadAndWriter interface { // 嵌套結構體
Reader
Writer
}
func (s Studenter) ReaderFunc() {
fmt.Println("呼叫ReaderFunc")
}
func (s Studenter) WriterFunc(str string) {
fmt.Println("呼叫 WriterFunc Str =", str)
}
func main() {
fmt.Println("草堂筆記(www.zhoubotong.site)")
// 必須實作嵌套的介面的所有方法,才算實作介面
var s interface{} // 定義介面型別變數s
var student Studenter // 定義 Studenter 結構體型別的變數 student
s = student // 將 Studenter 賦值給了變數 s
student.ReaderFunc() // 呼叫ReaderFunc方法
student.WriterFunc("這里是一段寫函式") // 呼叫WriterFunc方法
// 下面使用 介面型別斷言,分別判斷變數 s 是否是介面 Reader 、Writer 和 ReadAndWriter 型別
if reader, Ok := s.(Reader); Ok { // s 轉換成Reader 介面
fmt.Println("Studenter is type of Reader, Reader =", reader)
}
if writer, Ok := s.(Writer); Ok { // s 轉換成Writer 介面
fmt.Println("Studenter is type of Reader, Writer =", writer)
}
if readAndWriter, Ok := s.(ReadAndWriter); Ok {
fmt.Println("Studenter is type of Reader, ReadWriter =", readAndWriter)
}
}
輸出:
草堂筆記(www.zhoubotong.site)
呼叫ReaderFunc
呼叫 WriterFunc Str = 這里是一段寫函式
Studenter is type of Reader, Reader = {}
Studenter is type of Reader, Writer = {}
Studenter is type of Reader, ReadWriter = {}
上面student同時實作了介面中的Reader和Writer方法,我們發現變數 s 同時是 Reader 、Writer 和 ReadAndWriter 型別,即結構體 Studenter 同時實作了以上三個介面,
無論從事什么行業,只要做好兩件事就夠了,一個是你的專業、一個是你的人品,專業決定了你的存在,人品決定了你的人脈,剩下的就是堅持,用善良專業和真誠贏取更多的信任,其實這個例子就是用一個struct實作一個嵌套介面的方法,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/523093.html
標籤:其他
上一篇:【HDLBits刷題筆記】09 Latches and Flip-Flops
下一篇:day03-CSS
