Struct does not implement interface if it has a function which parameter implement interface

后端 未结 2 1725
余生分开走
余生分开走 2021-01-28 21:57

I have a package in which I have two interfaces

package main
type A interface {
    Close()
}
type B interface {
    Connect() (A, error)
}

I h

2条回答
  •  旧时难觅i
    2021-01-28 22:37

    The returned type for your Connect method should be A and not *C.

    The way you defined the Connect method is that it should return an interface, not a specific type. You will still be able to return *C as it implements the A interface.

    package main
    
    type A interface {
        Close()
    }
    
    type B interface {
        Connect() (A, error)
    }
    
    type C struct {
    }
    
    func (c *C) Close() {
    }
    
    type D struct {
    }
    
    func (d *D) Connect() (A, error) {
        c := new(C)
        println("successfully created new C:", c)
        return c, nil
    }
    
    func test(b B) {
        b.Connect()
    }
    
    func main() {
        d := new(D)
        test(d)
    }
    

    Outputs

    successfully created new C: 0xe28f0

    Try it out yourself here

提交回复
热议问题