go - 接口(interface)类型和值可以是不实现接口(interface)及其值的类型吗?

标签 go methods go-interface

这是我正在查看的代码和说明的链接: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

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

最佳答案

Spec: Method sets:

The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T).

[...] The method set of a type determines the interfaces that the type implements and the methods that can be called using a receiver of that type.

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

关于go - 接口(interface)类型和值可以是不实现接口(interface)及其值的类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55362410/

相关文章:

java - 在 Java 中合并 double 类型数组

php - 使用正则表达式验证类/方法名称

go - 类型转换接口(interface) slice

arrays - 使用一组键拆分对象数组

GoLang - 将 nil 传递给接受接口(interface)的函数

go - 无法构建具有外部模块本地副本的项目

go - 如何根据文件描述符的数量限制go例程

security - 是否在 golang 中缓冲了 http.Request.Body?

java - 找不到符号 - 方法 print()

go - 使用去范围变量的内存地址是否安全?