【问题标题】:Can interface type and value be a type that does not implement the interface and its value?接口类型和值可以是不实现接口及其值的类型吗?
【发布时间】:2019-03-26 16:52:47
【问题描述】:

这是我正在查看的代码和描述的链接:https://tour.golang.org/methods/11

我将 *T 类型的方法 M 更改为 T,即从指针接收器更改为值接收器,如下所示。

package main

import (
    "fmt"
    "math"
)

type I interface {
    M()
}

type T struct {
    S string
}

func (t T) M() {
    fmt.Println(t.S)
}

type F float64

func (f F) M() {
    fmt.Println(f)
}

func main() {
    var i I

    i = &T{"Hello"}
    describe(i)
    i.M()

    i = F(math.Pi)
    describe(i)
    i.M()
}

func describe(i I) {
    fmt.Printf("(%v, %T)\n", i, i)
}

但是,上面的更改给了我相同的结果,因为它仍然是一个指针接收器。

(&{Hello}, *main.T)
Hello
(3.141592653589793, main.F)
3.141592653589793

我不确定我是否理解了这个概念。根据我的理解,由于接口变量我得到了一个指向 struct T 实例的指针,该接口变量的类型应该是指向 struct T 的指针,并且由于指向 struct T 的指针没有实现方法 M,它会导致恐慌。

【问题讨论】:

    标签: go methods go-interface


    【解决方案1】:

    Spec: Method sets:

    对应的pointer type*T的方法集是所有用receiver*TT声明的方法的集合(即它还包含T的方法集)。

    [...] 一个类型的方法集决定了implements 类型的接口以及可以使用该类型接收器的called 的方法。

    所以你用值接收者声明的所有方法也将属于相应指针类型的方法集,因此非指针类型实现的所有接口也将由指针类型实现(可能更多)。

    【讨论】:

      【解决方案2】:

      Go 有一些快捷方式。例如:

      a.Method()
      a.Field
      

      相同
      (*a).Method()
      (*a).Field
      

      和这里的概念类似https://tour.golang.org/moretypes/4

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-15
        • 2019-02-10
        • 2019-06-27
        • 1970-01-01
        • 2012-10-24
        • 2011-06-15
        相关资源
        最近更新 更多