douyalin2258 2013-09-01 10:32
浏览 34
已采纳

入门:在struct上调用方法和在指向该struct的指针上调用方法之间有什么区别?

Supoose that I have a Vertex type

type Vertex struct {
    X, Y float64
}

and I've defined a method

func (v *Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

What's the difference between those two calls ? (both of them return the same result)

v1 := Vertex{3, 4}
fmt.Println(v1.Abs())

v2 := &Vertex{3, 4}
fmt.Println(v2.Abs())
  • 写回答

1条回答 默认 最新

  • douxi2670 2013-09-01 10:38
    关注

    The first version is the equivalent of

    var v1 Vertex
    v1.X = 3
    v1.y = 4
    fmt.Println((&v1).Abs)
    

    The second version is the equivalent of

    var v2 *Vertex
    v2 = new(Vertex)
    v2.X = 3
    v2.y = 4
    fmt.Println(v2.Abs)
    

    So the only substantial difference is that v1 is a value and v2 is a pointer to a value of type Vertex.

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

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示