gpt4 book ai didi

go - 为什么我们可以将结构指针分配给接口(interface)变量,即使结构指针没有实现接口(interface)?

转载 作者:行者123 更新时间:2023-12-01 22:10:36 25 4
gpt4 key购买 nike

我在下面介绍两个程序:程序 1 和程序 2。
我希望程序 1 无法编译,它确实无法编译。所以这很好。
我希望程序 2 无法编译,但它成功了!这个问题是关于为什么程序 2 会成功。
程序 1
https://play.golang.org/p/qX9nY8VLlx0

package main

import (
"fmt"
"math"
)

type Abser interface {
Abs() float64
}

type Vertex struct {
X float64
Y float64
}

func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
var a Abser

a = Vertex{3, 4}
fmt.Println(a.Abs())
}
这无法编译并出现此错误:
./prog.go:24:4: cannot use Vertex literal (type Vertex) as type Abser in assignment:
Vertex does not implement Abser (Abs method has pointer receiver)
我期待这个错误,因为 *Vertex实现 Abser但是 Vertex没有,所以我们不能分配 Vertex反对 Abser多变的。
节目二
https://play.golang.org/p/4bIs-fHGhYm
package main

import (
"fmt"
"math"
)

type Abser interface {
Abs() float64
}

type Vertex struct {
X float64
Y float64
}

func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
var a Abser

a = &Vertex{3, 4}
fmt.Println(a.Abs())
}
这样编译成功。程序的输出是:
5
为什么这会成功?在这里, Vertex实现 Abser但是 *Vertex未实现 Abser .然后我如何分配 *Vertex 类型的值?至 Abser ?
我需要了解哪些语言语义规则才能知道为什么会成功?

最佳答案

assignability需求说明了在接口(interface)的情况下需要什么:

A value x is assignable to a variable of type T ("x is assignable toT") if one of the following conditions applies:

...T is an interface type and x implements T....


为了确定“x 实现 T”的规则,我们转向 method sets 的概念。 :

A type may have a method set associated with it. The method set of aninterface type is its interface. The method set of any other type Tconsists of all methods declared with receiver type T.


乍一看,这意味着 Vertex的方法集在您的第一个示例中为空, *Vertex 的方法集在你的第二个例子中也是空的。
但是,规范继续指定:

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


这意味着 *Vertex 的方法集自动包含Vertex的方法集, 但不是相反 .
这对您的第一个示例没有帮助,但在第二个示例中, Vertex 的方法集包括 Abs() float64 .因为这就是实现 Abser 所需的全部内容。接口(interface), *Vertex被视为执行 Abser .

关于go - 为什么我们可以将结构指针分配给接口(interface)变量,即使结构指针没有实现接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63995894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com