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 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题