我目前正在学习用Go语言编程.我在理解Go指针方面遇到了一些困难(现在我的C/C++还很远......).例如,在Tour of Go#52(http://tour.golang.org/#52)中,我读到:
type Vertex struct {
X, Y float64
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main() {
v := &Vertex{3, 4}
fmt.Println(v.Abs())
}
Run Code Online (Sandbox Code Playgroud)
但如果不是
func (v *Vertex) Abs() float64 {
[...]
v := &Vertex{3, 4}
Run Code Online (Sandbox Code Playgroud)
我写:
func (v Vertex) Abs() float64 {
[...]
v := Vertex{3, 4}
Run Code Online (Sandbox Code Playgroud)
甚至:
func (v Vertex) Abs() float64 {
[...]
v := &Vertex{3, 4}
Run Code Online (Sandbox Code Playgroud)
反之亦然:
func (v *Vertex) Abs() float64 {
[...]
v := Vertex{3, …Run Code Online (Sandbox Code Playgroud) 鉴于golang巡回赛第54张幻灯片的设置:
type Abser interface {
Abs() float64
}
type Vertex struct {
X, Y float64
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
Run Code Online (Sandbox Code Playgroud)
为什么不能为结构以及指向结构的指针定义方法?那是:
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
Run Code Online (Sandbox Code Playgroud)
定义此方法会出现以下错误:
prog.go:41: method redeclared: Vertex.Abs
method(*Vertex) func() float64
method(Vertex) func() float64
Run Code Online (Sandbox Code Playgroud) 我只是通过Effective Go和Pointers vs. Values部分阅读,接近结尾它说:
有关接收器的指针与值的规则是可以在指针和值上调用值方法,但只能在指针上调用指针方法.这是因为指针方法可以修改接收器; 在值的副本上调用它们将导致丢弃这些修改.
为了测试它,我写了这个:
package main
import (
"fmt"
"reflect"
)
type age int
func (a age) String() string {
return fmt.Sprintf("%d yeasr(s) old", int(a))
}
func (a *age) Set(newAge int) {
if newAge >= 0 {
*a = age(newAge)
}
}
func main() {
var vAge age = 5
pAge := new(age)
fmt.Printf("TypeOf =>\n\tvAge: %v\n\tpAge: %v\n", reflect.TypeOf(vAge),
reflect.TypeOf(pAge))
fmt.Printf("vAge.String(): %v\n", vAge.String())
fmt.Printf("vAge.Set(10)\n")
vAge.Set(10)
fmt.Printf("vAge.String(): %v\n", vAge.String())
fmt.Printf("pAge.String(): %v\n", pAge.String())
fmt.Printf("pAge.Set(10)\n") …Run Code Online (Sandbox Code Playgroud)