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)
}
//NOTE: 对复杂类型进行修改,需要使用引用。否则操作的是副本,不会对该复杂对象生效
func (v *Vertex) Scale(f float64) {
//func (v Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
func main() {
v := Vertex{3, 4}
fmt.Println("v:",v)
v.Scale(10)
fmt.Println("v:",v)
fmt.Println(v.Abs())
}
[root@sltvb7v2wy3 jia_methods]# gor methods_pointrs.go
v: {3 4}
v: {30 40}
50
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)
}
//NOTE: 对复杂类型进行修改,需要使用引用。否则操作的是副本,不会对该复杂对象生效
//func (v *Vertex) Scale(f float64) {
func (v Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
func main() {
v := Vertex{3, 4}
fmt.Println("v:",v)
v.Scale(10)
fmt.Println("v:",v)
fmt.Println(v.Abs())
}
[root@sltvb7v2wy3 jia_methods]# vim methods_pointrs.go
[root@sltvb7v2wy3 jia_methods]# gor methods_pointrs.go
v: {3 4}
v: {3 4}
5
网友评论