This is a creation in Article, where the information may have evolved or changed.
Directory
-
- Method
- Concept
- Define Method
- Use Method
- To add a method to a type alias
Summary
Receiver, defining methods, using methods (2 forms), adding methods for type aliases
Method
Concept
- A method is a function that contains a hidden parameter (receiver).
- Method can only be defined for a type in the same package
ReceiverRefers to the subject of method dependencies
ReceiverCan be a value or a pointer
- No method overloads exist
Define Method
typestruct { string}//为 person 结构定义了一个 methodfuncprint() { fmt.Println("person")}
The above "P" is receiver, the body of the method
Note that because Go has no method overloads, the following methods are illegal
funcprint() { fmt.Println("person")}funcprintint) { fmt.Println("person")}
Use Method
The first way
"Jane"}p.print()
The second way
"Jane"}person.print(p)
To add a method to a type alias
type number int func (n number) Add10 () number {return n * ten }var N number = 5 var m = n.add10 () fmt. Println ( "n" , N) //n 5 FMT. Println ( "M" , m) //m