2016-06-07 104 views
2

新的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

+0

看看这个:http://stackoverflow.com/questions/28124412/how-to-implement-two-different-interfaces-with-the-same-method-signature –

回答

0

将接口视为契约。它们并不隐含地实现其他接口,仅仅是因为它们没有直接实现任何东西。

和接口满足的实现。 (希望这是有道理的)

在你的榜样,有简单的“材料”,这两个meachine类型的创建会的工作,如在此:https://play.golang.org/p/ZoYJog2Xri

package main 

type Machine1 interface { 
    Produce() Material 
} 

type Machine2 interface { 
    Produce() Material 
} 

type Material interface { 
    Use() error 
} 

type PencilMachine struct{} 

func (pm *PencilMachine) Produce() Material { 
    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 
} 
0

它,因为你的铅笔机没有实现机器2接口。这里是罪魁祸首:

func (pm *PencilMachine) Produce() Material1 { 
    return &Pencil{} 
} 

你看,虽然PencilMachine具有同样的功能Produce它不会返回相同的数据类型(Material1)为此其仅实现MACHINE1。 Machine2需要Produce函数返回Material2