Methods in Go: Enhancing Structs with Functionality
In Go, a function can be assigned to a struct, giving it the ability to perform actions related to its data. This concept is known as a method.
Let’s take a look at an example:
1 | type Person struct { |
In this example, we define a Person
struct with two fields, Name
and Age
. The Speak()
method is associated with the Person
struct and can be called on an instance of that struct. When flavio.Speak()
is called, it prints “Hello from Flavio” to the console.
Methods can be declared with either a pointer receiver or a value receiver.
In the above example, the method Speak()
is a value receiver. It receives a copy of the struct instance when called.
Alternatively, we can use a pointer receiver, which receives the pointer to the struct instance. Here’s an example:
1 | func (p *Person) Speak() { |
Using a pointer receiver enables us to modify the original struct instance. This can be useful when working with larger structs or when we want changes made within the method to reflect on the original instance.
By leveraging methods in Go, we can enhance our structs with custom functionality, making our code more organized and maintainable.
tags: [“Go programming”, “methods”, “struct methods”]