原文:http://golangtutorials.blogspot.com/2011/06/methods-on-structs.html

snmp 下载,有空学习一下!

https://sourceforge.net/projects/net-snmp/

--------------------------------------------------------------------------------------------------------

Methods on structs

 
We have learnt that structs can contain data. structs can also contain behavior in the form of methods. The definition of a method attached to or associated with a struct or any other type for that matter, is quite similar to a normal func definition, the only difference being that you need to additionally specify the type.

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 is: {4 3}
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 is: {4 3}
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 is: {4 3}
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]
}
cannot define new methods on non-local type time.Time

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
}
Full time now: Tue Nov 10 23:00:00 UTC 2009
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
}
Sum of forks and knives in house: 8

golang Methods on structs的更多相关文章

  1. 【转】java jawin api 中文 invoke方法

    org.jawin Class FuncPtr java.lang.Object org.jawin.FuncPtr ----------------------------------------- ...

  2. Inheritance and subclassing in Go - or its near likeness

    原文: http://golangtutorials.blogspot.com/2011/06/inheritance-and-subclassing-in-go-or.html ---------- ...

  3. golang embedded structs

    golang 中把struct 转成json格式输出 package main import ( "encoding/json" "fmt" ) type Pe ...

  4. 从OOP的角度看Golang

    资料来源 https://github.com/luciotato/golang-notes/blob/master/OOP.md?hmsr=toutiao.io&utm_medium=tou ...

  5. [转]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 ...

  6. Go语言(golang)开源项目大全

    转http://www.open-open.com/lib/view/open1396063913278.html内容目录Astronomy构建工具缓存云计算命令行选项解析器命令行工具压缩配置文件解析 ...

  7. [转]Go语言(golang)开源项目大全

    内容目录 Astronomy 构建工具 缓存 云计算 命令行选项解析器 命令行工具 压缩 配置文件解析器 控制台用户界面 加密 数据处理 数据结构 数据库和存储 开发工具 分布式/网格计算 文档 编辑 ...

  8. golang路上的小学生系列--使用reflect查找package路径

    本文同时发布在个人博客chinazt.cc 和 gitbook 今日看到了一个有趣的golang项目--kolpa(https://github.com/malisit/kolpa). 这个项目可以用 ...

  9. Golang 知识点总结

    Golang 知识点总结 目录 [−] 各种类型复制的时候的花费 可使用内建函数的类型 (len.cap.close.delete.make) 内建容器类型的值比较 组合类型T{...}的值比较 零值 ...

随机推荐

  1. linux 大量time_wait的解决方法

    通过调整内核参数解决vi /etc/sysctl.conf 编辑文件,加入以下内容:net.ipv4.tcp_syncookies = 1net.ipv4.tcp_tw_reuse = 1net.ip ...

  2. keepalived+lvs tcp check 引起的后端服务报Connection reset by peer

    方法一: 取消LVS方式进行tcp转发,进而改为http方式反向代理,问题即可解决. 当然,这是在业务允许使用http的情况下,如果必须使用tcp协议,那就得使用下面的方法了. 方法二: 修改keep ...

  3. JavaScript图形实例:图形的旋转变换

    旋转变换:图形上的各点绕一固定点沿圆周路径作转动称为旋转变换.可用旋转角表示旋转量的大小. 旋转变换通常约定以逆时针方向为正方向.最简单的旋转变换是以坐标原点(0,0)为旋转中心,这时,平面上一点P( ...

  4. 开启Hadoop和Spark的学习之路

    Hadoop Hadoop是一个由Apache基金会所开发的分布式系统基础架构. 用户可以在不了解分布式底层细节的情况下,开发分布式程序.充分利用集群的威力进行高速运算和存储. Hadoop实现了一个 ...

  5. LVS-TUN模式

    TUN模式: 其实数据转发原理和上图是一样的,不过这个我个人认为主要是位于不同位置(不同机房):LB是通过隧道进行了信息传输,虽然增加了负载,可是因为地理位置不同的优势,还是可以参考的一种方案: 优点 ...

  6. mysql索引 多个单列索引和联合索引的区别详解

    背景: 为了提高数据库效率,建索引是家常便饭:那么当查询条件为2个及以上时,我们是创建多个单列索引还是创建一个联合索引好呢?他们之间的区别是什么?哪个效率高呢?我在这里详细测试分析下. 一.联合索引测 ...

  7. How George Washington Angered Lawmakers Over Thanksgiving——VOA慢速英语

    听力地址:How George Washington Angered Lawmakers Over Thanksgiving 中英对照:华盛顿总统将感恩节定为全国性节日 Words in This S ...

  8. (二)Spring Boot 官网文档学习之入门

    文章目录 Spring Boot 是什么 系统要求 Servlet 容器 Maven方式安装Spring Boot 编写第一个 Spring Boot 项目 原文:https://docs.sprin ...

  9. 01 IO流(一)—— 流的概念、File类

    1 流的概念理解(重要) 理解流的概念非常重要. 流,就是程序到数据源或目的地的一个通道. 我们把这个通道实例化得到一个具体的流,相当于一个数据传输工具,它可以在程序与资源之间进行数据交换. 换言之, ...

  10. 搭建hexo静态博客

    使用hexo搭建博客,并将博客部署到github 需要的工具 Node.js Git 一个Github账号 正式开始 在任意目录下新建一个文件夹,如blog,在该文件夹下右键打开git bash he ...