在结构体(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

你可能感兴趣的:(在结构体(struct)中内嵌 接口(interface))