Defining and Invoking Struct Methods
In the previous section, we introduced the concept of struct methods in Go. Now, let's dive deeper into how to define and invoke these methods.
Defining Struct Methods
To define a struct method, you use the func
keyword, followed by the method name, a receiver parameter (which is the struct instance that the method operates on), and the method body. The receiver parameter can be either a pointer to the struct or a value of the struct, depending on your needs.
Here's an example of defining a Greet()
method for the Person
struct:
type Person struct {
Name string
Age int
}
func (p *Person) Greet() {
fmt.Printf("Hello, my name is %s and I'm %d years old.\n", p.Name, p.Age)
}
In this example, the Greet()
method is defined as a pointer receiver, which means it operates on a pointer to a Person
struct. This allows the method to modify the struct's fields, if necessary.
Invoking Struct Methods
To invoke a struct method, you use the dot (.
) operator to call the method on an instance of the struct. Here's an example:
func main() {
person := Person{
Name: "Alice",
Age: 30,
}
person.Greet() // Output: Hello, my name is Alice and I'm 30 years old.
}
In this example, we create a Person
struct instance and then call the Greet()
method on it.
You can also invoke struct methods using a pointer to the struct instance:
func main() {
person := &Person{
Name: "Alice",
Age: 30,
}
person.Greet() // Output: Hello, my name is Alice and I'm 30 years old.
}
In this case, the compiler automatically dereferences the pointer and calls the Greet()
method on the underlying Person
struct.
Defining and invoking struct methods is a fundamental concept in Go programming, and it's essential for building modular and maintainable code. In the next section, we'll explore some more advanced concepts related to struct methods.