本文介绍了为什么在直接实现的接口上的此类型声明失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使用Go的Type Assertion机制.在下面的示例中,Qux.(Bar)的类型声明失败.

I am struggling with Go's Type Assertion mechanism. In the below example the Type Assertion for Qux.(Bar) fails.

为什么在Qux处直接实现DoBar()不能完全填充Bar接口?

Why does a direct implementation of DoBar() at Qux not fullfill the Bar interface?

软件包主要

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.DoBar()具有指针接收器,因此只有*Qux实现了Bar,而没有实现Qux.类型Qux和指向它的指针类型*Qux是不同的类型,具有不同的方法集.

Qux.DoBar() has pointer receiver, so only *Qux implements Bar but not Qux. The type Qux and the pointer type to it *Qux are different types with different method sets.

使用类型为*Qux的值会实现Bar:

Using a value of type *Qux does implement Bar:

Check(&Qux{bar: bar{name: "*Qux"}})

此输出(在游乐场上尝试):

*Qux has Nameable
*Qux has Bar: DoBar

此外,如果您将Qux.DoBar()的接收者更改为非指针:

Also if you change the receiver of Qux.DoBar() to be non-pointer:

func (q Qux) DoBar() string {
    return "DoBar"
}

然后Qux*Qux都将实现Bar:

Check(bar{name: "bar"})
Check(Qux{bar: bar{name: "Qux"}})
Check(&Qux{bar: bar{name: "*Qux"}})

输出(在游乐场上尝试):

bar has Nameable
Qux has Nameable
Qux has Bar: DoBar
*Qux has Nameable
*Qux has Bar: DoBar

请参阅相关问题: X没有实现Y(...方法具有指针接收器)

这篇关于为什么在直接实现的接口上的此类型声明失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-20 03:00