【发布时间】:2018-06-13 06:27:40
【问题描述】:
我想组成另一种类型的类型,但是用假的替换其中一个字段(这是一个接口值)。我遇到的问题是正在使用基础字段,所以我似乎无法覆盖该字段。
我在这里演示了这个问题:https://play.golang.org/p/lHGnyjzIS-Y
package main
import (
"fmt"
)
type Printer interface {
Print()
}
type PrinterService struct {}
func (ps PrinterService) Print() { fmt.Println("PrinterService") }
type Service struct {
Client PrinterService
}
func (s Service) PrintViaMethod() { s.Client.Print() }
type FakeService struct {
Service
Client Printer
}
type SomeOtherService struct {}
func (sos SomeOtherService) Print() { fmt.Println("SomeOtherService") }
func main() {
s := FakeService{Client: SomeOtherService{}}
s.PrintViaMethod()
}
为什么打印"PrinterService"?我希望它打印"SomeOtherService"。
谢谢。
【问题讨论】:
标签: go struct interface embedding overriding