dongyu1614 2018-09-04 08:37
浏览 4
已采纳

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

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
", v, v.Abs())
  v.Scale(5)
  fmt.Printf("After scaling: %+v, Abs: %v
", v, v.Abs())
    fmt.Println(reflect.TypeOf(Vertex{3,4}))
}

Hello, I am learning golang now. I do not understand what is the use of adding "&", if it does not make any change on the result value?

I thought we add "&" to variables to get the memory address. If we can add "&" to Vertex{3,4}, does this mean it is variable? Confused.

  • 写回答

1条回答 默认 最新

  • dongtangu8615 2018-09-04 08:39
    关注

    I assume you're talking about Vertex vs &Vertex? Yes, adding & means that v now contains an address to a struct of type Vertex, whereas without the &, v would hold the struct directly.

    In your example, using the address, or the struct directly, makes no difference. In many other cases, the distinction is very important.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图问题
  • ¥15 有段代码不知道怎么理解,const isToken = (config.headers || {}).isToken === false
  • ¥100 采用栈和深度优先算法对我的代码进行修改显示路径
  • ¥15 pointnet2包安装
  • ¥20 射频功率问题,解答者有酬谢!
  • ¥80 构建降雨和积水的预测模型
  • ¥15 #Qt Transform setTransform()在鼠标拖动移动视角是一致在原地不动,无法变换视角(细微观察似乎视图有在原地抖动),无法变换视角(细微观察似乎视图有在原地抖动)
  • ¥50 如何利用无人机拍摄的数码照片测量鸟卵的长短径
  • ¥100 github贡献者给与奖励
  • ¥15 使用DS18B20+ESP8266获取温度数据返回-127.00