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) 我在下面有这个简单的程序
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,Done和Wait函数采用*sync.WaitGroup.
为什么/这是如何工作的?
根据对这个问题的回应
有关接收器的指针与值的规则是可以在指针和值上调用值方法,但只能在指针上调用指针方法
但实际上我可以对非指针值执行指针方法:
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)
那么,这里有什么问题?这是一个新功能吗?或者对问题的回答是错误的?