Methods: Attaching Behavior to Structs
Swipe to show menu
When you need to associate specific behaviors with a struct in Go, you use methods. A method in Go is a function that has a special receiver argument, which allows you to tie the function directly to a struct type. This design lets you encapsulate logic relevant to a data type, making your code easier to read, maintain, and reason about.
The syntax for a method looks similar to a standard function, but with one key difference: it includes a receiver specification between the func keyword and the method name. The receiver is often a short, lowercase variable name representing the struct, followed by the struct type itself in parentheses. For example, func (u User) DisplayName() string declares a method named DisplayName with a receiver of type User.
Go encourages idiomatic method naming: method names should clearly describe the action or information provided, and should not redundantly mention the struct type. For example, DisplayName is preferred over UserDisplayName when the method is attached to the User struct.
Let's look at a practical example demonstrating how to define and use a method on a struct.
main.go
1234567891011121314151617181920package main import ( "fmt" ) type User struct { FirstName string LastName string } // DisplayName returns the full display name of the user. func (u User) DisplayName() string { return u.FirstName + " " + u.LastName } func main() { user := User{FirstName: "Jane", LastName: "Doe"} fmt.Println(user.DisplayName()) }
In this example, you define a User struct with two fields: FirstName and LastName. The DisplayName method is attached to the User type, using u User as the receiver. When you call user.DisplayName(), the method accesses the fields of the User instance (u) and returns the full name as a single string.
Here's a step-by-step breakdown of how the DisplayName method works:
- The method is declared with a receiver, so it can access the struct's fields directly;
- The method combines
FirstNameandLastNameusing string concatenation; - The method returns the resulting string as the user's display name;
- You invoke the method on any
Uservalue, and it automatically uses the correct data for that specific instance.
You should use methods when the function logically belongs to a typeโwhen it operates on or returns information about the data in the struct. This approach keeps related logic close to the data it modifies or describes. In contrast, standalone functions are best for operations that don't require access to a struct's internal fields or when the function is generic and not tied to a specific type.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat