Junior — Middle
What is the difference between a method and a function, and what are the features of their use?
sobes.tech AI
Answer from AI
In Go, a function is an independent block of code that can be called by name and can accept parameters and return values.
A method is a function associated with a specific type (for example, a struct). A method is declared with a receiver, which determines to which type it belongs.
Features of usage:
- A method allows working with data of a specific type, using the receiver inside the method body.
- Methods help organize code and implement behavior for types, bringing Go closer to object-oriented style.
Example:
package main
import "fmt"
type Person struct {
Name string
}
// Method with receiver of type Person
func (p Person) Greet() {
fmt.Println("Hello, my name is", p.Name)
}
// Regular function
func Add(a, b int) int {
return a + b
}
func main() {
p := Person{Name: "Ivan"}
p.Greet() // calling the method
fmt.Println(Add(2, 3)) // calling the function
}