Introduction
Structs are a composite data type in Go used to create custom data structures that group related variables under a single type. In this guide, we'll explore how to define and work with structs, providing sample code to demonstrate their usage.
Defining Structs
In Go, you can define a struct using the type
keyword followed by the struct's name and a list of fields. Here's an example:
package main
import "fmt"
// Define a struct named "Person" with fields "Name" and "Age".
type Person struct {
Name string
Age int
}
func main() {
// Create an instance of the "Person" struct.
person := Person{
Name: "Alice",
Age: 30,
}
fmt.Println("Name:", person.Name)
fmt.Println("Age:", person.Age)
}
In this code, we define a struct called "Person" with two fields: "Name" and "Age." We then create an instance of the "Person" struct and access its fields.
Anonymous Structs
Go allows you to create anonymous structs, which are structs without a predefined name. They are useful for one-time data grouping. Here's an example:
package main
import "fmt"
func main() {
// Create an anonymous struct.
person := struct {
Name string
Age int
}{
Name: "Bob",
Age: 25,
}
fmt.Println("Name:", person.Name)
fmt.Println("Age:", person.Age)
}
In this code, we create an anonymous struct to represent a person and access its fields.
Methods on Structs
You can define methods for your custom struct types in Go. Methods are functions associated with a struct, and they enable you to perform operations on struct instances. Here's an example:
package main
import "fmt"
type Rectangle struct {
Width float64
Height float64
}
// Define a method "Area" for the "Rectangle" struct.
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func main() {
rect := Rectangle{Width: 5, Height: 3}
area := rect.Area()
fmt.Println("Rectangle Area:", area)
}
In this code, we define a method called "Area" for the "Rectangle" struct to calculate the area of a rectangle.
Further Resources
To continue learning about Go structs and custom data types, consider these resources:
- Go Tour - More Types: Structs, Slices, and Maps - An interactive online tutorial for learning Go structs.
- Effective Go - Structs - Official Go documentation on structs.