美文网首页golang
golang笔记之指针使用

golang笔记之指针使用

作者: 仰望夜空一万次 | 来源:发表于2019-05-07 10:57 被阅读0次

    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

    相关文章

      网友评论

        本文标题:golang笔记之指针使用

        本文链接:https://www.haomeiwen.com/subject/ldteoqtx.html