相关疑难解决方法(0)

用对象调用指针接收器的方法而不是指向它的指针?

v是指针的对象Vertex,并且Scale是指针的方法Vertex.那么为什么v.Scale(10)没有错,因为它v不是指向Vertex对象的指针?谢谢.

package main

import (
    "fmt"
    "math"
)

type Vertex struct {
    X, Y float64
}

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

func (v *Vertex) Scale(f float64) {
    v.X = v.X * f
    v.Y = v.Y * f
}

func main() {
    v := Vertex{3, 4}
    v.Scale(10)
    fmt.Println(v.Abs())
}
Run Code Online (Sandbox Code Playgroud)

methods pointers function call go

5
推荐指数
2
解决办法
191
查看次数

`sync.WaitGroup` 的方法集是什么?

我在下面有这个简单的程序

package main

import (
    "fmt"
    "sync"
    "time"
)

var wg sync.WaitGroup

func main() {
    wg.Add(1)

    go func() {
        fmt.Println("starting...")
        time.Sleep(1 * time.Second)
        fmt.Println("done....")
        wg.Done()
    } ()

    wg.Wait()

}
Run Code Online (Sandbox Code Playgroud)

请注意,我var wg sync.WaitGroup用作值,而不是指针。但是同步包页面指定Add,DoneWait函数采用*sync.WaitGroup.

为什么/这是如何工作的?

go

5
推荐指数
1
解决办法
1165
查看次数

非指针类型的指针方法

根据对这个问题的回应

有关接收器的指针与值的规则是可以在指针和值上调用值方法,但只能在指针上调用指针方法

但实际上我可以对非指针值执行指针方法:

package main

import "fmt"

type car struct {
    wheels int
}

func (c *car) fourWheels() {
    c.wheels = 4
}

func main() {

    var c = car{}
    fmt.Println("Wheels:", c.wheels)
    c.fourWheels()
    // Here i can execute pointer method on non pointer value
    fmt.Println("Wheels:", c.wheels)
}
Run Code Online (Sandbox Code Playgroud)

那么,这里有什么问题?这是一个新功能吗?或者对问题的回答是错误的?

methods pointers go

3
推荐指数
1
解决办法
690
查看次数

标签 统计

go ×3

methods ×2

pointers ×2

call ×1

function ×1