The difference between Go functions and methods is that the function is defined outside the package and does not receive a receiver; while the method is defined within the type and receives the type receiver as the first parameter.
#How to distinguish between Go functions and methods?
In the Go language, although functions and methods look similar, there are essential differences between them.
Function
func Greet(name string) string { return "Hello, " + name + "!" }
Method
type Person struct { Name string } func (p Person) Greet() string { return "Hello, " + p.Name + "!" }
Practical case
The following code demonstrates the difference between functions and methods:
package main import "fmt" func main() { // 调用函数 greeting1 := Greet("Alice") fmt.Println(greeting1) // 输出:Hello, Alice! // 实例化类型并调用方法 alice := Person{Name: "Alice"} greeting2 := alice.Greet() fmt.Println(greeting2) // 输出:Hello, Alice! } func Greet(name string) string { return "Hello, " + name + "!" } type Person struct { Name string } func (p Person) Greet() string { return "Hello, " + p.Name + "!" }
The above is the detailed content of How to distinguish golang functions and methods?. For more information, please follow other related articles on the PHP Chinese website!