go - 为什么我们在下面的脚本中添加 &,如果它对结果没有任何改变?
问题描述
package main
import (
"fmt"
"math"
"reflect"
)
type Vertex struct {
X, Y float64
}
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main() {
v := &Vertex{3, 4} // Whether or not with "&", the values don't change below.
fmt.Printf("Before scaling: %+v, Abs: %v\n", v, v.Abs())
v.Scale(5)
fmt.Printf("After scaling: %+v, Abs: %v\n", v, v.Abs())
fmt.Println(reflect.TypeOf(Vertex{3,4}))
}
你好,我现在正在学习golang。我不明白添加“&”有什么用,如果它不对结果值进行任何更改?
我以为我们在变量中添加“&”来获取内存地址。如果我们可以在 Vertex{3,4} 中添加“&”,这是否意味着它是可变的?使困惑。
解决方案
我假设你在谈论Vertex
vs &Vertex
?是的,添加&
意味着v
现在包含类型结构的地址Vertex
,而没有&
,v
将直接保存结构。
在您的示例中,直接使用地址或结构没有区别。在许多其他情况下,区别非常重要。
推荐阅读
- ruby-on-rails - Rails 删除单个上传的主动存储问题
- reactjs - 上下文 `router.history` 在 `Link` 中被标记为必需,但其值为 `undefined`
- php - 删除数组和数组 Laravel 中的值
- php - echo mysql 导致 $mail-> PHPMailer 的正文
- react-native - 如何将文档从反应原生 DocumentPicker 响应发送到 web api 作为字节 []
- java - 第 n 个数字,具有两个设置位 n,范围从 1 到 10^14
- html - HTML 下拉菜单
- r - R中Rle对象的滚动平均值
- reactjs - ReactJS 表单数据不正确
- maven - 在 JFrog Artifactory 中创建远程存储库时如何仅接受 https url