Function and method are two different concepts in Go language. Receiver: Functions do not have receivers, while methods do. Callability: A function can be called only by a type name, whereas a method can be called by a type or variable name. Access control: Functions can only access parameters and global variables, while methods can access private fields of the receiver.
In Go language, function and method are two different concepts, respectively for different purposes scenes to be used. This article will delve into the key differences between them and illustrate them with practical examples.
Functions are independent blocks of code that perform specific tasks. They are declared by the keyword func
, followed by the function name, parameter list, and return type.
func sum(a, b int) int { return a + b }
Methods are functions associated with a specific type. They are defined by placing a receiver parameter before the receiver type. The receiver parameter can be a pointer (*T
) or a value (T
).
type Point struct { x, y int } func (p *Point) Scale(factor int) { p.x *= factor p.y *= factor }
The main difference between functions and methods is:
Consider a simple shape interface and a Rectangle
Type:
type Shape interface { Area() float64 } type Rectangle struct { width, height float64 } func (r Rectangle) Area() float64 { return r.width * r.height }
In this code , Shape
is an interface that defines an Area
method. Rectangle
is a structure that implements the Shape
interface and provides a specific implementation of the Area
method.
We can use the function PrintArea
that accepts any Shape
type and prints its area:
func PrintArea(s Shape) { fmt.Printf("Area: %.2f\n", s.Area()) }
by calling the Rectangle
instance With the Area
method, we can calculate and print the area of a rectangle:
rect := Rectangle{width: 5, height: 10} PrintArea(&rect) // 使用指针调用方法(因为 Rectangle 是值类型)
Functions and methods are different concepts in the Go language and are used for different purposes. Understanding the differences between them is crucial to using the Go language effectively. Functions are used for independent tasks, while methods are used for tasks associated with a specific type. By understanding these differences, you can write Go code that is clearer, maintainable, and scalable.
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!