Learn how to use structs (`struct`) and their methods in Go.
A struct (`struct`) is a way to group multiple variables under the same type. It is used to model complex objects.
type Person struct {
Name string
Age int
}
In Go, you can attach methods to a struct to give it behavior:
func (p Person) Introduce() {
fmt.Println("Hello, my name is", p.Name, "and I am", p.Age, "years old.")
}
structs.go
.package main
import "fmt"
type Person struct {
Name string
Age int
}
func (p Person) Introduce() {
fmt.Println("Hello, my name is", p.Name, "and I am", p.Age, "years old.")
}
func main() {
p1 := Person{"Alice", 25}
p1.Introduce()
}
Hello, my name is Alice and I am 25 years old.
📚 Learn more about structs in Go:
Read the official documentation🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊