cnruby的个人博客分享 http://blog.sciencenet.cn/u/cnruby 铁皮石斛兰与我的生活

博文

习与学Go语言:类型的方法(一)

已有 1576 次阅读 2018-7-26 15:41 |个人分类:软件与编程|系统分类:科研笔记| Golang, tutorial, 入门, tutorial, tutorial

 

### 代码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




https://blog.sciencenet.cn/blog-659727-1126029.html

上一篇:网站天地:Ruby语言日期时间格式化函数strftime
收藏 IP: 222.143.25.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-3-29 16:37

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部