Я борюсь с механизмом утверждения типа Go. В приведенном ниже примере утверждение типа для Qux.(Bar)
не выполняется.
Почему прямая реализация DoBar()
в Qux
не заполняет интерфейс Bar
?
основной пакет
import (
"fmt"
)
type Nameable interface {
Name() string
}
type Foo interface {
Nameable
DoFoo() string
}
type Bar interface {
Nameable
DoBar() string
}
type bar struct {
name string
}
func (b bar) Name() string {
return b.name
}
// Qux embeds bar and is expected to fullfill Nameable interface
type Qux struct {
bar
}
func (q *Qux) DoBar() string {
return "DoBar"
}
func Check(subject Nameable) {
if N, ok := subject.(Nameable); ok {
fmt.Printf("%s has Nameable\n", N.Name())
}
if F, ok := subject.(Foo); ok {
fmt.Printf("%s has Foo: %s\n", F.Name(), F.DoFoo())
}
if B, ok := subject.(Bar); ok {
fmt.Printf("%s has Bar: %s\n", B.Name(), B.DoBar())
}
}
func main() {
Check(bar{name: "bar"})
Check(Qux{bar: bar{name: "Qux"}})
}
https://play.golang.org/p/PPkUMUu58JW
Выход:
bar has Nameable
Qux has Nameable
Qux
терпит неудачу при утверждении типаsubject.(Bar)
, хотя реализует самDoBar()
?! - person Christian Schmizz   schedule 10.10.2018