|||
### 代码methods.go
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 main() { vertex := Vertex{3, 4} fmt.Println(vertex.Abs()) }
### 执行代码
mkdir bin go build -o ./bin/methods methods.go ./bin/methods
### 学习要点
- 如何定义类型(type .. struct)上的方法(func)
- 如何定义类型Vertex的实例变量vertex
- 如何使用类型Vertex的方法Abs
### 关键词
- methods types function receiver "methods on types"
- 类型 方法 接收者 函数
### 代码说明
- 方法名称:Abs
- 类型名称:Vertex
- 方法Abs的接收者参数类型:Vertex
- 方法Abs是定义于类型Vertex的函数
- 方法Abs的接收者实例变量名称:v
- 类型Vertex的实例变量名称:vertex
### 代码解说
- 接收者类型Vertex可以理解为一种“类”
- 定义于类型Vertex的函数Abs可以理解为该“类”的方法
- 类型Vertex的实例变量vertex可以理解为该“类”的对象
### 参考资料
- http://go-tour-zh.appspot.com/methods/1
- https://tour.golang.org/methods/1
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-10-20 03:47
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社