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
原创粉丝点击