去基础 : What is the diference between calling a method on struct and calling it on a pointer to that struct?

标签 go

假设我有一个 Vertex 类型

type Vertex struct {
    X, Y float64
}

我已经定义了一个方法

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

这两个调用有什么区别? (两者返回相同的结果)

v1 := Vertex{3, 4}
fmt.Println(v1.Abs())

v2 := &Vertex{3, 4}
fmt.Println(v2.Abs())

最佳答案

第一个版本相当于

var v1 Vertex
v1.X = 3
v1.y = 4
fmt.Println((&v1).Abs)

第二个版本相当于

var v2 *Vertex
v2 = new(Vertex)
v2.X = 3
v2.y = 4
fmt.Println(v2.Abs)

因此,唯一的实质区别是 v1 是一个值,而 v2 是指向 Vertex 类型值的指针。

关于去基础 : What is the diference between calling a method on struct and calling it on a pointer to that struct?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18557537/

相关文章:

go - Gorm WHERE子句不适用于预加载数据

Go - map 值不更新

go - chromedp 收到无效的 CSRF token 错误; Puppeteer 和浏览器都可以

json - Go - JSON解码器没有初始化我的结构

golang 区分 IPv4 IPv6

go - reflect.TypeOf((*error)(nil)).Elem()` 是什么意思?

templates - GoLang 在模板索引中挂起

mongodb - 需要在 MongoDB 和 golang(mgo) 中使用 $push 包含 $each 和 $position

去测试从 VS 代码到终端的不可重现的输出

go - 我们可以像在 python 中那样在 Go 中创建上下文管理器吗?