新的Go。我试图编写一个测试,涉及嘲笑一些结构的功能之一返回其他结构的实例的结构。但是我遇到,我可以用下面的代码重现的问题:实现相同接口的不同返回值的接口转换
package main
type Machine1 interface {
Produce() Material1
}
type Machine2 interface {
Produce() Material2
}
type Material1 interface {
Use() error
}
type Material2 interface {
Use() error
}
type PencilMachine struct{}
func (pm *PencilMachine) Produce() Material1 {
return &Pencil{}
}
type Pencil struct{}
func (p *Pencil) Use() error {
return nil
}
func main() {
pm := new(PencilMachine)
var m1 Machine1
m1 = Machine1(pm)
var m2 Machine2
m2 = Machine2(m1)
_ = m2
}
其中提供了以下错误:
prog.go:38: cannot convert m1 (type Machine1) to type Machine2:
Machine1 does not implement Machine2 (wrong type for Produce method)
have Produce() Material1
want Produce() Material2
注意如何铅笔结构实现两个Material1和材料2接口。但是(pm * PencilMachine)Produce()的返回类型是Material1而不是Material2。好奇为什么这不起作用,因为实现Material1的任何东西都实现了Material2。
谢谢!
https://play.golang.org/p/3D2jsSLoI0
看看这个:http://stackoverflow.com/questions/28124412/how-to-implement-two-different-interfaces-with-the-same-method-signature –