golang笔记之指针使用

Choosing a value or pointer receiver

There are two reasons to use a pointer receiver.

  • The first is so that the method can modify the value that its receiver points to.

  • The second is to avoid copying the value on each method call. This can be more efficient if the receiver is a large struct, for example.

package main

import (
    "fmt"
    "math"
)

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}
    fmt.Printf("Before scaling: %+v, Abs: %v\n", v, v.Abs())
    v.Scale(5)
    fmt.Printf("After scaling: %+v, Abs: %v\n", v, v.Abs())
}

In this example, both Scale and Abs are with receiver type *Vertex, even though the Abs method needn't modify its receiver.

In general, all methods on a given type should have either value or pointer receivers, but not a mixture of both. (We'll see why over the next few pages.)

参考:
https://tour.golang.org/methods/8

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • 标签(空格分隔): 编程 Go官方文档 Using the tour 1.1 Hello, 世界 Welcome...
    uangianlap阅读 1,553评论 0 5
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,939评论 0 23
  • 我们在快节奏的生活里。似乎希望结果也是快餐化,可以快速的看到自己想要的结果。 谈恋爱急着想要结婚,结了婚张快点要宝...
    起飞瞬间阅读 124评论 0 0
  • 在生活中,没有任何东西比人的行动更重要、更珍奇了。 01 时隔一年后,我又再一次开始写作,内心很忐忑,很害怕会又再...
    大方柒柒阅读 640评论 0 4