![]() |
VOOZH | about |
Go methods are like functions but with a key difference: they have a receiver argument, which allows access to the receiver's properties. The receiver can be a struct or non-struct type, but both must be in the same package. Methods cannot be created for types defined in other packages, including built-in types like int or string; otherwise, the compiler will raise an error.
Name: a Age: 25
func(receiver_name Type) method_name(parameter_list) (return_type) {
// Code
}
Table of Content
In Go, you can define a method where the receiver is of a struct type. The receiver is accessible inside the method. The previous example showcases this approach with a struct type receiver.
Go also allows methods with non-struct type receivers, as long as the receiver's type and method definition are present in the same package. You cannot define a method with a receiver type from another package (e.g., int, string).
Using the same example above, we can demonstrate a method with a non-struct receiver:
Square of 4 is 16
In Go, methods can have pointer receivers. This allows changes made in the method to reflect in the caller, which is not possible with value receivers.
func (p *Type) method_name(...Type) Type { // Code}Before: a After: b
Unlike functions, Go methods can accept both value and pointer receivers. You can pass either a pointer or a value, and the method will handle it accordingly.
After pointer method: b Name: b
| Method | Function |
|---|---|
| Contains a receiver | Does not contain a receiver |
| Methods with the same name but different types can be defined in the program | Functions with the same name but different types are not allowed |
| Cannot be used as a first-order object | Can be used as first-order objects |