search

What is the difference between Go's methods and functions?

In Go, both functions and methods are used to define reusable pieces of code. However, there are some differences between the two.

Functions are standalone blocks of code that can be called from anywhere in the program. They are defined with the **func** keyword followed by the function name, the list of arguments in parentheses, and the return type. 

Here's an example:

func add(x, y int) int {
    return x + y
}

Methods, on the other hand, are functions that are associated with a particular type or struct. They are defined with the **func** keyword followed by the receiver type, the function name, the list of arguments in parentheses, and the return type. Here's an example:

type Person struct {
    name string
    age int
}

func (p Person) greet() {
    fmt.Printf("Hello, my name is %s and I'm %d years old.", p.name, p.age)
}

In this example, **greet** is a method associated with the **Person** struct. The **p** before the function name specifies that this method belongs to the **Person** struct.

Another difference between methods and functions is that methods can access and modify the fields of the struct they are associated with, while functions cannot. Additionally, methods can be called using the dot notation, like this:

p := Person{name: "Alice", age: 30}
p.greet()

This would call the **greet** method associated with the **Person** struct and print the message "Hello, my name is Alice and I'm 30 years old."

In summary, the main differences between functions and methods are that methods are associated with a specific type or struct, can access and modify its fields, and can be called using the dot notation. Functions, on the other hand, are standalone blocks of code that can be called from anywhere in the program.

Related Questions You Might Be Interested