This is a creation in
Article, where the information may have evolved or changed.
The syntax of method is as follows:
Func (R receivertype) methodName (parameters) (results)
The method in go is attached to a given type, and his syntax is almost the same as the declaration syntax of the function, except that a receiver is added before the method name, that is, the subject that method is attached to (which can be understood in object-oriented objects)
For example, the following example:
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 This method is attached to the structure of box. The issuer of the box.volume is that Box,volume is a method of box, not a peripheral function.
To be more precise, box has three fields width, heigh, depth, and a method volume (), and these methods and fields belong to box.
When using method, there are several points to note:
1, the method can be the same name, then if the recipient is not the same, then the method is not the same
2. The method can access the recipient's field
3. Call method through. Access, just like accessing a field in a struct
The following is a more complex example:
Package Mainimport "FMT" const (white = iotablackblueredyellow) type Color bytetype Box struct {width, heigh, depth float64c Olor 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.volu Me () > 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 stri Ngs[c]}func Main () {boxes: = Boxlist{box{4, 4, 4, white},box{10, 1, blue},box{1, 1, ten, Black},box{4, 4, 4, red},box{2 0, White},box{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 in is", Boxes[len (boxes) -1].color. String ()) fmt. Println ("The biggest 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 ())}