This is a creation in Article, where the information may have evolved or changed.
You can define as many as you want in any custom type method
, so let's take a look at a more complicated example.
Package Mainimport ' FMT ' const (white = Iota BLACK BLUE RED YELLOW) type Color bytetype Box struct {width , height, depth float64 color Color}type boxlist []box//a slice of Boxesfunc (b Box) Volume () float64 {return b.wi DTH * B.height * B.DEPTH}FUNC (b *box) SetColor (c Color) {B.color = C}func (bl boxlist) Biggestscolor () Color {V: = 0.00 K: = Color (White) for _, B: = range bl {if b.volume () > v {v = b.volume () k = B.color}} return K}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, RED}, box{10, 1, YELLOW}, Bo X{1, 1, BLACK}, Box{10, ten, 1, BLUE}, box{10, 1, white}, box{20, (+), 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 (), "³") fmt. PRINTLN ("The color of the last one is", Boxes[len (boxes) -1].color. String ()) fmt. Println ("The biggest one is", boxes. Biggestscolor (). String ()) fmt. PRINTLN ("Let's paint them All Black") boxes. Paintitblack () fmt. PRINTLN ("The color of the second one is", Boxes[1].color. String ()) fmt. Println ("Obviously, now, the biggest one is", boxes. Biggestscolor (). String ())}
The above code defines some constants through const, and then defines some custom types
- Color as an alias for Byte
- Defines a struct:box that contains three long and wide fields and a color property
- Defines a slice:boxlist that contains box
It then defines some method for the recipient with the custom type above
- Volume () defines the receiver as box and returns the capacity of box
- SetColor (c color), change the box color to C
- Biggestscolor () on Boxlist, returns the largest color in the list
- Paintitblack () Turn all the box colors in Boxlist into black
- String () defines the specific color (string format) of the color above the color
Is it easy to describe the above code after it is written? Our general problem solving is through the description of the problem, to write the corresponding code implementation.
Pointer as Receiver
Now let's go back and look at SetColor, whose receiver is a pointer to Box, yes, you can use *box. Think about why you should use pointers instead of box itself.
We define the real purpose of setcolor is to change the box color, if not pass the box pointer, then SetColor accept is actually a box copy, that is, in the method of the color value of the modification, in fact, only action on the box copy, Rather than the real box. So we need to pass in pointers.
This can be used as the first parameter of method, and then combined with the previous function to explain the value and pass the reference is not difficult to understand
Here you might ask that the SetColor function should be defined in this way, *b.Color=c
not b.Color=c
because we need to read the corresponding value of the pointer.
You are right, in fact go inside both of these methods are correct, when you use the pointer to access the corresponding field (although the pointer does not have any fields), go know you want to pass the pointer to get this value, see, go design is more and more attracted you.
Perhaps the attentive reader will ask such questions, Paintitblack inside call SetColor when should be written (&bl[i]).SetColor(BLACK)
, because SetColor receiver is *box, not Box.
You're right, either way, because go knows receiver is a pointer and he automatically helps you.
Other words:
If receiver of a method is *t, you can call this method on an instance variable V of type T, without requiring &v to call this method
Similar to
If receiver of a method is T, you can call this method on a variable p of *t type, without needing *p to call this method
So, you don't have to worry about whether you're calling a pointer to a method or a pointer to Method,go know what you're going to do, this is a great pain for a classmate with years of experience in C + + programming.
Method inheritance
In the previous chapter, we learned the inheritance of the field, then you will also find a magic of Go, method can also inherit. If an anonymous field implements a method, the struct that contains the anonymous field can also invoke the method. Let's take a look at the following example
package mainimport "fmt"type Human struct { name string age int phone string}type Student struct { Human //匿名字段 school string}type Employee struct { Human //匿名字段 company string}//在human上面定义了一个methodfunc (h *Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)}func main() { mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"} sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"} mark.SayHi() sam.SayHi()}
Method rewrite
In the above example, what if Emplyee wants to implement his own sayhi? Simple, as with anonymous field conflicts, we can define a method on Emplyee that overrides anonymous fields. Take a look at the following example
package mainimport "fmt"type Human struct { name string age int phone string}type Student struct { Human //匿名字段 school string}type Employee struct { Human //匿名字段 company string}//Human定义methodfunc (h *Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)}//Employee的method重写Human的methodfunc (e *Employee) SayHi() { fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name, e.company, e.phone) //Yes you can split into 2 lines here.}func main() { mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"} sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"} mark.SayHi() sam.SayHi()}
The above code design is so wonderful, let people unconsciously for go design Marvel!
Through this, we can design the basic object-oriented program, but go inside the object-oriented is so simple, there is no private, public key, by the case of the implementation (uppercase beginning of the common, lowercase beginning of the private), methods also apply this principle.