gpt4 book ai didi

go - 将方法转换为 func var

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

为什么将方法分配给函数处理程序有效。

短链接:https://play.golang.org/p/UEYGCpMgyV6

package main

import (
"fmt"
"math"
)

type Vertex struct {
X, Y float64
}

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

func Abs() float64 {
return math.Sqrt(10)
}

func AbsFloat(f float64) float64 {
return math.Sqrt(f)
}

func main() {
v := Vertex{3, 4}

// Assigning Abs() to func handler.
var absFunc func() float64 = Abs
fmt.Println(absFunc())

// Wrong type as expected.
//absFunc = AbsFloat

// Assigning method to func handler works, why ?
absFunc = v.Abs

// Changing receiver args. Useful for unittesting but why/how this works ?
v.X = 1
v.Y = 1
fmt.Println(absFunc())
}

它是 Golang 类型检查“功能” func()float64 == func(T)float64 还是其他?请帮助理解这个概念。

最佳答案

v.Abs 是一个 method value ,并引用规范:

The method value x.M is a function value that is callable with the same arguments as a method call of x.M.

方法值具有与没有接收者的方法相同的参数和结果类型的函数类型。

关于go - 将方法转换为 func var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54361697/

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