The difference between methods and functions
What is the method? How to use it?
Methods: Apply to the specified data type, that is, bind to the specified data type, so custom types can have methods, not just structs
Use of methods:
Func (A A) test(){fmt.println (a.num)}Copy the code
Method call procedure and parameter passing mechanism
The difference between method and function parameters:
Similarity: When a method is called from a variable, it is called by the same mechanism as a function
Difference: When a variable calls a method, the variable itself is passed to the method as an argument (copied if the variable is of value type, copied if it is of reference type).
Method considerations
-
If a structure type is a value type, it is copied in a method call, following the pass-value mechanism.
-
If you want to change the value of a variable in a method, you can do so by changing the pointer to the structure (more efficiently).
-
Methods in Golang work on the specified data class (bound to the specified data type), so custom types can have methods, not just structs such as int, Float32, etc
type integer int func (i integer) print(){ fmt.Println("i=",i) } func main(){ var i integer = 10 i.print() } Copy the code
-
Methods use the same rules for access control scope as functions: methods start with a lowercase letter and can only be accessed within this package, and methods start with an uppercase letter and can be accessed within this package and other packages
-
If a type implements the String() method, fmt.println calls the String() output of that variable by default
The difference between methods and functions
-
Different invocation methods
How a function is called: function name (argument list)
Method invocation: variable. Method name (argument list)
-
For normal functions, data of a pointer type cannot be passed directly when the receiver is a value type: value types can only be passed value types, and pointer types can only be passed pointer types
-
For methods, when the receiver is of a magnitude type, the method can be called directly using a variable of pointer type, and vice versa