zoukankan      html  css  js  c++  java
  • A Tour of Go Methods with pointer receivers

    Methods can be associated with a named type or a pointer to a named type.

    We just saw two Abs methods. One on the *Vertex pointer type and the other on the MyFloat value type.

    There are two reasons to use a pointer receiver. First, to avoid copying the value on each method call (more efficient if the value type is a large struct). Second, so that the method can modify the value that its receiver points to.

    Try changing the declarations of the Abs and Scale methods to use Vertex as the receiver, instead of *Vertex.

    The Scale method has no effect when v is a VertexScale mutates v. When v is a value (non-pointer) type, the method sees a copy of the Vertex and cannot mutate the original value.

    Abs works either way. It only reads v. It doesn't matter whether it is reading the original value (through a pointer) or a copy of that value.

    package main 
    
    import (
        "fmt"
        "math"
    )
    
    type Vertex struct {
        X, Y float64
    }
    
    func (v *Vertex) Scale(f float64) {
        v.X = v.X * f
    }
    func (v *Vertex) Abs() float64{
        return math.Sqrt(v.X*v.X + v.Y*v.Y)
    }
    
    func main() {
        v := &Vertex{3, 4}
        v.Scale(5)
        fmt.Println(v, v.Abs())
    }
    package main 
    
    import (
        "fmt"
        "math"
    )
    
    type Vertex struct {
        X, Y float64
    }
    
    func (v Vertex) Scale(f float64) {
        v.X = v.X * f
    }
    func (v Vertex) Abs() float64{
        return math.Sqrt(v.X*v.X + v.Y*v.Y)
    }
    
    func main() {
        v := &Vertex{3, 4}
        v.Scale(5)
        fmt.Println(v, v.Abs())
    }
  • 相关阅读:
    有关数据库锁表
    order by 排序的数字异常
    索引建议
    有关文件在浏览器中打开window.open
    vscode 常用快捷键
    jQuery中preventDefault()、stopPropagation()、return false 之间的区别
    理解Linux系统负荷(WDCP系统后台参数之一)
    JavaScript toString() 方法
    1-4:CSS3课程入门之文本新增属性
    1-3:CSS3课程入门之伪类和伪元素
  • 原文地址:https://www.cnblogs.com/ghgyj/p/4057649.html
Copyright © 2011-2022 走看看