GO面向对象:method
来源:互联网 发布:python android 逆向 编辑:程序博客网 时间:2024/06/08 02:28
method的语法如下:
func (r ReceiverType) methodName(parameters) (results)
go中的method是附属在一个给定的类型上的,他的语法和函数的声明语法几乎一样,只是在方法名之前增加了一个receiver,也就是method所依附的主体(可以面向对象中的对象理解)
例如下面的例子:
type Box struct {width, heigh, depth float64}func (b Box) Volume() float64 {return b.width * b.heigh * b.depth}func main(){ b:=Box{4,4,4} volume:=b.Volume()}
Volume这个method是依附于Box这个结构的。Box.Volume的发出者是Box,Volume是属于Box的方法,而不是一个外围函数。
更确切的说,Box拥有三个字段width, heigh, depth,同时拥有一个方法Volume(),这些方法和字段都属于Box。
使用method的时候,需要注意一下几点:
1、method的名字可以一样,当时如果接受者不一样,那么method就不一样
2、method里可以访问接受者的字段
3、调用method通过.访问,就像访问struct里的字段一样
下面是一个较为复杂的例子:
package mainimport "fmt"const (WHITE = iotaBLACKBLUEREDYELLOW)type Color bytetype Box struct {width, heigh, depth float64color Color}type BoxList []Boxfunc (b Box) Volume() float64 {return b.width * b.heigh * b.depth}func (b *Box) SetColor(c Color) {b.color = c}func (bl BoxList) BiggestBox() Box {v := 0.0var box = bl[0]for _, b := range bl {if b.Volume() > v {v = b.Volume()box = b}}return box}func (bl BoxList) PaintItBlack() {for i, _ := range bl {bl[i].SetColor(BLACK)}}func (c Color) String() string {strings := []string{"WHITE", "BLACK", "BLUE", "RED", "YELLOW"}return strings[c]}func main() {boxes := BoxList{Box{4, 4, 4, WHITE},Box{10, 10, 1, BLUE},Box{1, 1, 20, BLACK},Box{4, 4, 4, RED},Box{20, 20, 20, WHITE},Box{100, 100, 100, RED},Box{3, 3, 3, YELLOW},}fmt.Printf("We have %d boxes in our set\n", len(boxes))fmt.Println("The volume of the first one is", boxes[0].Volume(), "cm3")fmt.Println("The color of the last on is", boxes[len(boxes)-1].color.String())fmt.Println("The biggest on is", boxes.BiggestBox().color.String())fmt.Println("Let's paint them all black")boxes.PaintItBlack()fmt.Println("The color of the second box is", boxes[1].color.String())fmt.Println("Obviously, now, the biggest on is ", boxes.BiggestBox().color.String())}
0 0
- GO面向对象:method
- GO面向对象:method的继承和重写
- GO面向对象
- go语言面向对象
- go语言 面向对象
- Go面向对象编程
- GO语言面向对象
- go基础-面向对象
- go面向对象编程
- Go基础学习-面向对象
- go语言的面向对象
- Go语言面向对象编程
- go语言中的面向对象
- Go语言学习 面向对象
- GO语言中的面向对象与接口
- Go语言与面向对象编程
- go学习【三】面向对象啊
- 神奇的go语言(面向对象)
- 观察者模式
- Python语言实践分析 -- 包导入
- laravel之发送邮件
- 蓝桥杯 带分数(搜索)
- 带你学习JQuery:事件冒泡和阻止默认行为
- GO面向对象:method
- android-WebView拦截JavaScript
- php和java的区别(个人感想)
- Webkit内核的学习
- JavaScript中的原型和对象机制
- Android基础之Intent详解
- asp.net导出.TXT文件
- window.addEventListener来解决让一个js事件执行多个函数
- web.config配置数据库连接