首页 > 解决方案 > 为什么我们在下面的脚本中添加 &,如果它对结果没有任何改变?

问题描述

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} 中添加“&”,这是否意味着它是可变的?使困惑。

标签: go

解决方案


我假设你在谈论Vertexvs &Vertex?是的,添加&意味着v现在包含类型结构的地址Vertex,而没有&,v将直接保存结构。

在您的示例中,直接使用地址或结构没有区别。在许多其他情况下,区别非常重要。


推荐阅读