在結構體(struct)中內嵌 接口(interface)

代碼

https://github.com/fengchunjian/goexamples/tree/master/struct_embeded_interface

package main

import "fmt"

type Printer interface {
    Print()
}

type CanonPrinter struct {
    printerName string
}

func (printer CanonPrinter) Print() {
    fmt.Println(printer.printerName, "print.")
}

type PrintWoker struct {
    Printer
    name string
    age  int
}

func main() {
    canon := CanonPrinter{printerName: "canon_1"}
    printWorker := PrintWoker{Printer: canon, name: "Zhang", age: 21}
    printWorker.Printer.Print()
}

執行

go run printer.go
canon_1 print.

參考文檔

golang 中的內嵌(embeded)
https://studygolang.com/articles/6934

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容