美文网首页
在结构体(struct)中内嵌 接口(interface)

在结构体(struct)中内嵌 接口(interface)

作者: 莫名FCJ | 来源:发表于2017-11-15 14:24 被阅读176次

代码

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)

      本文链接:https://www.haomeiwen.com/subject/zencvxtx.html