This is a creation in Article, where the information may have evolved or changed.
The syntax of method is as follows:
func (r ReceiverType) funcName(parameters) (results)
Let's do this in the first example using method:
package mainimport (" FMT "" math ") type Rectangl e struct {width, height float64}type Circle struct {radius float64}func (r Rectangle) area () Float64 {return R . Width*r.height}func (c Circle) area () float64 {return C.radius * C.radius * Math. Pi}func Main () {r1: = rectangle{12, 2} r2: = Rectangle{9, 4} c1: = circle{10} c2: = circle{25} fmt. Println ("Area of R1 is:", R1.area ()) fmt. Println ("Area of R2 is:", R2.area ()) fmt. Println ("Area of C1 is:", C1.area ()) fmt. Println ("Area of C2 is:", C2.area ())}
Important points to note when using method
- Although the name of the method is identical, the method is different if the recipient is different
- You can access the recipient's field in the method
- Call method
. is accessed, just like a struct inside a field
This is illustrated below:
Figure 2.9 different struct's method
One thing to note is that the method shown in the illustration is marked with a dashed line, meaning that receiver is passed by value, not by reference, yes, receiver can also be a pointer, the difference between The pointer acts as receiver on the contents of the instance object, while the normal type acts as receiver only as a copy of the Operation object and does not operate on the original instance object. This will be discussed in detail later in this article.
Is that method only works on a struct? Of course not, he can be defined in any of your custom types, built-in types, structs and other types above. Are you a little confused here, what is a custom type, a custom type is not a struct, it's not like that. Struct is just a special type of custom type, and there are other custom type declarations that can be implemented with the following declarations.
type typeName typeLiteral
Take a look at the following code that declares a custom type
type ages inttype money Float32type months map[ STRING]INTM: = months {"January": +, "February": 28, ... "December": ~,}