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 关于#wireshark#的问题:并且能够给数据做标注,如这个流量是在看视频或者是在转账
  • ¥90 请问,这个视频播放软件的名称,用过的朋友请给答案,上方..avi是啥意思?是看短剧还是播放本地视频?
  • ¥15 运筹优化,gurobi,python
  • ¥15 基于python的电影系统推荐
  • ¥20 springmvc重定向和返回json
  • ¥15 数学建模——参会安排怎么做
  • ¥15 电脑键盘实现触摸功能
  • ¥25 matlab无法将表达式转换为双数组怎么解决?
  • ¥15 单片机汇编语言相关程序
  • ¥20 家用射频美容仪技术规格