doumao8803 2018-10-10 12:12
浏览 61
已采纳

为什么在直接实现的接口上的此类型声明失败?

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

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

package main

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.Name())
    } 

    if F, ok := subject.(Foo); ok {
        fmt.Printf("%s has Foo: %s
", F.Name(), F.DoFoo())
    }

    if B, ok := subject.(Bar); ok {
        fmt.Printf("%s has Bar: %s
", B.Name(), B.DoBar())
    }
}

func main() {
    Check(bar{name: "bar"})
    Check(Qux{bar: bar{name: "Qux"}})
}

https://play.golang.org/p/PPkUMUu58JW

Output:

bar has Nameable
Qux has Nameable
  • 写回答

1条回答 默认 最新

  • dougu1045 2018-10-10 12:45
    关注

    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.

    Using a value of type *Qux does implement Bar:

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

    This outputs (try it on the Go Playground):

    *Qux has Nameable
    *Qux has Bar: DoBar
    

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

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

    Then both Qux and *Qux will implement Bar:

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

    Output (try it on the Go Playground):

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

    See related question: X does not implement Y (... method has a pointer receiver)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示