GO面向对象:method

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 main

import "fmt"

const (
	WHITE = iota
	BLACK
	BLUE
	RED
	YELLOW
)

type Color byte

type Box struct {
	width, heigh, depth float64
	color               Color
}

type BoxList []Box

func (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.0
	var 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())

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值