golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
122.68k stars 17.49k forks source link

Covariation does not work on the return value. #42307

Closed XORveRCOM closed 3 years ago

XORveRCOM commented 3 years ago

It is inconvenient.

package main

type Sub struct {}

type ISub interface {}

type Base struct {
    sub *Sub
}

type IBase interface {
    Sub() ISub
}

func (b *Base) Sub() *Sub {
    return b.sub
}

func main() {
    var s *Sub
    s = &Sub{}
    var si ISub
    si = s
    var b IBase
    b = &Base{sub:s}
}
./prog.go:25:4: cannot use &Base literal (type *Base) as type IBase in assignment:
    *Base does not implement IBase (wrong type for Sub method)
        have Sub() *Sub
        want Sub() ISub
mvdan commented 3 years ago

The Go project doesn't use the issue tracker for questions. See https://golang.org/wiki/Questions.

If you want to propose a language change, file a proposal issue with https://github.com/golang/proposal/blob/master/go2-language-changes.md.