golang Methods on structs
原文:http://golangtutorials.blogspot.com/2011/06/methods-on-structs.html
snmp 下载,有空学习一下!
https://sourceforge.net/projects/net-snmp/

--------------------------------------------------------------------------------------------------------
Methods on structs
A normal function that we name my_func that takes no parameters and returns an int would be defined similar to that shown below.
Partial code
func my_func() int {
//code
}
A function or method that we name my_func that takes no parameters and returns an int, but which is associated with a type we name my_type would be defined similar to that shown below.
Partial code
type my_type struct { }
func (m my_type) my_func() int {
//code
}
Let’s extend our earlier Rectangle struct to add an Area function. This time we will define that the Area function works explicitly with the Rectangle type with func (r Rectangle) Area() int.
Full code
package main
import "fmt"
type Rectangle struct {
length, width int
}
func (r Rectangle) Area() int {
return r.length * r.width
}
func main() {
r1 := Rectangle{4, 3}
fmt.Println("Rectangle is: ", r1)
fmt.Println("Rectangle area is: ", r1.Area())
}
Rectangle area is: 12
Many object oriented languages have a concept of this or self that implicitly refers to the current instance. Go has no such keyword. When defining a function or method associated with a type, it is given as a named variable - in this case (r Rectangle) and then within the function the variable r is used.
In the above call to Area, the instance of Rectangle is passed as a value. You could also pass it by reference. In calling the function, there would be no difference whether the instance that you call it with is a pointer or a value because Go will automatically do the conversion for you.
Full code
package main
import "fmt"
type Rectangle struct {
length, width int
}
func (r Rectangle) Area_by_value() int {
return r.length * r.width
}
func (r *Rectangle) Area_by_reference() int {
return r.length * r.width
}
func main() {
r1 := Rectangle{4, 3}
fmt.Println("Rectangle is: ", r1)
fmt.Println("Rectangle area is: ", r1.Area_by_value())
fmt.Println("Rectangle area is: ", r1.Area_by_reference())
fmt.Println("Rectangle area is: ", (&r1).Area_by_value())
fmt.Println("Rectangle area is: ", (&r1).Area_by_reference())
}
Rectangle area is: 12
Rectangle area is: 12
Rectangle area is: 12
Rectangle area is: 12
In the above code, we have defined two similar functions, one which takes the Rectangle instance as a pointer and one that takes it by value. We have called each of the functions, via a value r1 and once as an address &r1. The results however are all the same since Go performs appropriate conversions.
Just to extend the example, let’s do one more function that works on the same type. In the below example, we ‘attach’ a function to calculate the perimeter of the Rectangle type.
Full code
package main
import "fmt"
type Rectangle struct {
length, width int
}
func (r Rectangle) Area() int {
return r.length * r.width
}
func (r Rectangle) Perimeter() int {
return 2* (r.length + r.width)
}
func main() {
r1 := Rectangle{4, 3}
fmt.Println("Rectangle is: ", r1)
fmt.Println("Rectangle area is: ", r1.Area())
fmt.Println("Rectangle perimeter is: ", r1.Perimeter())
}
Rectangle area is: 12
Rectangle perimeter is: 14
You might be tempted now to see if you can attach methods and behavior to any type, say like an int or time.Time - not possible. You will be able to add methods for a type only if the type is defined in the same package.
Partial code
func (t time.Time) first5Chars() string {
return time.LocalTime().String()[0:5]
}
However, if you absolutely need to extend the functionality, you can easily use what we learnt about anonymous fields and extend the functionality.
Full code
package main import "fmt"
import "time" type myTime struct {
time.Time //anonymous field
} func (t myTime) first5Chars() string {
return t.Time.String()[0:5]
} func main() {
m := myTime{*time.LocalTime()} //since time.LocalTime returns an address, we convert it to a value with *
// m := myTime{time.Now()} 这行是对的!!!!!!!!!!
fmt.Println("Full time now:", m.String()) //calling existing String method on anonymous Time field
fmt.Println("First 5 chars:", m.first5Chars()) //calling myTime.first5Chars
}
First 5 chars: Tue N
Methods on anonymous fields
There was another item that we slipped into the previous program - method calls on anonymous fields. Since time.Time was an anonymous field within myTime, we were able to refer to a method of Time as if it were a method of myTime. i.e. we were able to do myTime.String(). Let’s do one program using an earlier example.
In the following code we go back to our house where we have a Kitchen as an anonymous field in House. As we learnt with member fields, we can also access methods of anonymous fields as if they belong directly to the composing type. So House has an anonymous Kitchen which in turn has a method totalForksAndKnives(); so now House.totalForksAndKnives() is a valid call.
Full code
package main
import "fmt"
type Kitchen struct {
numOfForks int
numOfKnives int
}
func(k Kitchen) totalForksAndKnives() int {
return k.numOfForks + k.numOfKnives
}
type House struct {
Kitchen //anonymous field
}
func main() {
h := House{Kitchen{4, 4}} //the kitchen has 4 forks and 4 knives
fmt.Println("Sum of forks and knives in house: ", h.totalForksAndKnives()) //called on House even though the method is associated with Kitchen
}
golang Methods on structs的更多相关文章
- 【转】java jawin api 中文 invoke方法
org.jawin Class FuncPtr java.lang.Object org.jawin.FuncPtr ----------------------------------------- ...
- Inheritance and subclassing in Go - or its near likeness
原文: http://golangtutorials.blogspot.com/2011/06/inheritance-and-subclassing-in-go-or.html ---------- ...
- golang embedded structs
golang 中把struct 转成json格式输出 package main import ( "encoding/json" "fmt" ) type Pe ...
- 从OOP的角度看Golang
资料来源 https://github.com/luciotato/golang-notes/blob/master/OOP.md?hmsr=toutiao.io&utm_medium=tou ...
- [转]50 Shades of Go: Traps, Gotchas, and Common Mistakes for New Golang Devs
http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/ 50 Shades of Go: Traps, Gotc ...
- Go语言(golang)开源项目大全
转http://www.open-open.com/lib/view/open1396063913278.html内容目录Astronomy构建工具缓存云计算命令行选项解析器命令行工具压缩配置文件解析 ...
- [转]Go语言(golang)开源项目大全
内容目录 Astronomy 构建工具 缓存 云计算 命令行选项解析器 命令行工具 压缩 配置文件解析器 控制台用户界面 加密 数据处理 数据结构 数据库和存储 开发工具 分布式/网格计算 文档 编辑 ...
- golang路上的小学生系列--使用reflect查找package路径
本文同时发布在个人博客chinazt.cc 和 gitbook 今日看到了一个有趣的golang项目--kolpa(https://github.com/malisit/kolpa). 这个项目可以用 ...
- Golang 知识点总结
Golang 知识点总结 目录 [−] 各种类型复制的时候的花费 可使用内建函数的类型 (len.cap.close.delete.make) 内建容器类型的值比较 组合类型T{...}的值比较 零值 ...
随机推荐
- 第07组 Alpha冲刺(3/4)
队名:秃头小队 组长博客 作业博客 组长徐俊杰 过去两天完成的任务:完成人员分配,初步学习Android开发 Github签入记录 接下来的计划:继续完成Android开发的学习,带领团队进行前后端开 ...
- views 视图层
Django的View(视图) 一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应. 响应可以是一张网页的HTML内容,一个重定向,一个404错误, ...
- [转帖]五分钟彻底搞懂你一直没明白的Linux内存管理
五分钟彻底搞懂你一直没明白的Linux内存管理 https://cloud.tencent.com/developer/article/1462476 现在的服务器大部分都是运行在Linux上面的,所 ...
- python基础学习(十)
21.文件操作 # r只读 w只写(原来文件会消失!!!,也可以创建新文件) a追 # 加 r+ 读写 story_file = open("Story.txt", "r ...
- Hystrix【入门】
公共依赖配置: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spr ...
- 有关同时进行两条线路的四维dp
今天发现自己完全对这种dp没有思路……我果然太蒻了./落泪.jpg 对于一个N*N的方格图中选择两条线路从左上角到右下角,其实只要用一个数组f[i][j][p][q]记录一个人走到(i,j)另一个人走 ...
- 20191031:Python底层机制
20191031:Python底层机制 python底层从3个方面来说,分别是: 引用计数机制 垃圾回收机制 内存池机制 引用计数机制 使用引用计数来追踪内存中的对象,所有对象都有引用计数,并且这个引 ...
- SAS学习笔记47 Macro Quoting
简单来说:Macro Quoting就是将具有特殊功能字符及字母组合的特殊功能隐藏掉.例如:让分号(;)不再表示一个语句的结束,而就是一个普普通通的字符:让GE不再表示大于等于的比较符,而就是两个普普 ...
- mtd-utils 的 使用
关于编译可以查看文章:<Arm-Linux 移植 mtd-utils 1.x> 查看信息 使用命令前用cat /proc/mtd 查看一下mtdchar字符设备:或者用ls -l /dev ...
- DataSource配置
一.JDBC Jar依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifac ...