2016-06-07 2 views
2

new to Go. 구조체 함수 중 하나가 다른 구조체의 인스턴스를 반환하는 몇 가지 구조체를 조롱하는 테스트를 작성하려고합니다. 그러나 나는 다음과 같은 코드를 재현 할 수있는 문제로 실행 해요 :동일한 인터페이스를 구현하는 다른 반환 값을 사용하는 인터페이스 변환

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 

공지 방법 연필 구조체 구현은 모두 재료 1과 Material2에 인터페이스 : 다음과 같은 오류를 제공

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 
} 

합니다. 그러나 (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

그것의 당신의 연필 기계가 구현하지 않기 때문에을 Machine2 인터페이스. 그것은 단지 머신 1을 구현

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

당신은 PencilMachine이 같은 기능 Produce를 가지고 있지만이 같은 데이터 유형 (재료 1)를 반환하지 않는 것을 볼 그에 : 여기에 범인입니다. Machine2는 Material2를 반환하기 위해 Produce 함수가 필요합니다.

관련 문제