Functions and methods are two ways to define code blocks in Go. Function scope is global or package private, and method scope is type private. Functions do not have receiver parameters, whereas methods have receiver parameters that allow access to type members. The practical case shows the average calculation function without using a structure, and the weighted average calculation method using a structure.
The difference between functions and methods in Go
Introduction
In the Go language, functions and methods are two ways of defining code blocks. While there are many similarities, they also have fundamental differences. This article will dive into the differences between functions and methods in Go and provide practical examples.
Function
A function is a type-independent block of code that performs some operation on input and returns output. Functions are defined using the func
keyword, followed by the function name, parameter list, and return value type.
Example:
func sum(a, b int) int { return a + b }
Call function:
result := sum(10, 20)
Method
Method is appended to a function on the type. It allows instances of the type to access and manipulate the method's implementation. Methods are defined using receiver parameters, followed by the method name, parameter list, and return value type.
Example:
type Person struct { Name string } func (p Person) Greet() string { return "Hello, " + p.Name + "!" }
Calling method:
p := Person{"John"} greeting := p.Greet()
Difference
Characteristics | Function | Method |
---|---|---|
func
|
| |
Global, Package Private | Type Private | |
None | Yes | |
No | Yes |
## Calculate the average
Without using a structure, you can write a function to calculate the average of an array of floating point numbers:func Avg(numbers []float64) float64 { sum := 0.0 for _, num := range numbers { sum += num } return sum / float64(len(numbers)) }
type WeightedAvg struct { Numbers []float64 Weights []float64 } func (w WeightedAvg) Avg() float64 { weightedSum := 0.0 for i := range w.Numbers { weightedSum += w.Numbers[i] * w.Weights[i] } totalWeight := 0.0 for _, w := range w.Weights { totalWeight += w } return weightedSum / totalWeight }
The above is the detailed content of What is the difference between golang functions and methods?. For more information, please follow other related articles on the PHP Chinese website!