In Go, a method is a function with a special receiver argument, which defines the method on a specific type. Unlike functions, which can be called directly, methods are called with the object they belong to (the receiver). This distinction allows methods to access and manipulate the receiver’s data.
To declare a method, define a receiver type and a receiver variable within the parentheses just before the function name. The receiver type can be a defined custom struct or any other named type (except for pointer and interface types).
Here’s a basic example of a struct and a method:
type Point struct {
X float64
Y float64
}
func (p Point) DistanceFromOrigin() float64 {
return math.Sqrt(p.X*p.X + p.Y*p.Y)
}
In this example, ‘DistanceFromOrigin‘ is a method with receiver type ‘Point‘ and receiver variable ‘p‘.
Now let’s compare functions and methods:
1. Syntax: Functions are declared with the ‘func‘ keyword, followed by the function name, parameters, and return type(s). Methods also use the ‘func‘ keyword, but they have a receiver type and receiver variable before the method name.
Function:
func FullName(firstName, lastName string) string {
return firstName + " " + lastName
}
Method:
func (p Person) FullName() string {
return p.firstName + " " + p.lastName
}
2. Calling: Functions are called by their name and passing arguments directly. Methods are called on a specific instance of the receiver type, using dot notation.
Function call:
name := FullName("John", "Doe")
Method call:
p := Person{"John", "Doe"}
name := p.FullName()
3. Context: Methods have access to the receiver’s data, allowing them to manipulate the state of the receiver, whereas functions can only operate on the passed arguments.
4. Extension: While functions can be implemented in any context, methods are only available to the defined receiver type, enabling a clear differentiation of responsibilities.
Here’s an illustration to summarize the difference between functions and methods:
| Aspect | Function | Method |
|---|---|---|
| Syntax Definition | func name(parameters) returnTypes | func (receiverType) name(parameters) returnTypes |
| Calling | name(arguments) | receiverInstance.name(arguments) |
| Scope and Context | Independent of types | Tied to the receiver type |
In conclusion, methods in Go are a way to group related operations on a specific type, allowing for more organized and object-oriented programming. They differ from functions mainly in their declaration syntax, calling methodology, and context.