【发布时间】:2016-06-07 04:04:58
【问题描述】:
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
注意 Pencil 结构体是如何实现 Material1 和 Material2 接口的。但是 (pm *PencilMachine) Produce() 的返回类型是 Material1 而不是 Material2。很好奇为什么这不起作用,因为实现 Material1 的任何东西也实现了 Material2。
谢谢!
【问题讨论】:
标签: go