2018-09-04 08:37 浏览 1

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

package main
import (
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())
  fmt.Printf("After scaling: %+v, Abs: %v
", v, v.Abs())

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 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.

    点赞 评论 复制链接分享