为什么我们在以下脚本中添加&,如果它没有对结果进行任何更改? [关闭]

问题描述 投票:-5回答:1
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
1个回答
4
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.