gpt4 book ai didi

go - 接收方是否确定应用哪种方法?

转载 作者:数据小太阳 更新时间:2023-10-29 03:32:40 24 4
gpt4 key购买 nike

围棋之旅:https://tour.golang.org/methods/9

package main

import (
"fmt"
"math"
)

type Abser interface {
Abs() float64
}

func main() {
var a Abser
f := MyFloat(-math.Sqrt2)
v := Vertex{3, 4}

a = f // a MyFloat implements Abser
a = &v // a *Vertex implements Abser

// In the following line, v is a Vertex (not *Vertex)
// and does NOT implement Abser.
a = v

fmt.Println(a.Abs())
}

type MyFloat float64

func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}

type Vertex struct {
X, Y float64
}

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

在这个练习中,有两个 Abs() 方法。但似乎第 24 行 fmt.Println(a.Abs()) 自动应用了具有与变量相同类型的接收器的那个。

这是接收器的特性吗?

最佳答案

The Go Programming Language Specification

Method sets

A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other type T consists of all methods declared with receiver type T. 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). Further rules apply to structs containing embedded fields, as described in the section on struct types. Any other type has an empty method set. In a method set, each method must have a unique non-blank method name.

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.


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.

例如,简化Go Tour的例子,

package main

import (
"fmt"
"math"
)

type Abser interface {
Abs() float64
}

type Vertex struct {
X, 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} // a *Vertex implements Abser
fmt.Println(a.Abs())
}

Playground :https://play.golang.org/p/cf3WMcBI0WJ

输出:

5

Abser 类型的变量 a 可以包含任何具有 Abser 方法集的变量类型:Abs() float64。变量 a 包含一个 *Vertex 满足 Abser 方法集 func (v *Vertex) Abs() float64 .表达式 a.Abs() 为其当前包含的类型 *Vertex 执行方法 Abs()

关于go - 接收方是否确定应用哪种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51135292/

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