Structs in Go
Introduction to Structs
Structs in Go allow you to define complex data types by grouping variables of different types together. They are useful for representing real-world entities.
Defining and Using a Struct
Structs are defined using the type
keyword followed by the struct name and fields.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Alice", Age: 25}
fmt.Println(p)
}
This example defines a Person
struct and initializes it with values.
Accessing and Modifying Struct Fields
Fields of a struct can be accessed and modified using dot notation.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Alice", Age: 25}
fmt.Println("Before update:", p.Name, p.Age)
p.Age = 30 // Updating the Age field
fmt.Println("After update:", p.Name, p.Age)
}
Here, we update Alice’s age from 25 to 30.
Structs with Methods
Structs in Go can have methods, which are functions with a receiver.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func (p Person) Greet() {
fmt.Println("Hello, my name is", p.Name)
}
func main() {
p := Person{Name: "Alice", Age: 25}
p.Greet()
}
This example adds a Greet
method to the Person
struct.
Pointers to Structs
Structs can be used with pointers to modify values directly.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func (p *Person) IncreaseAge() {
p.Age++
}
func main() {
p := Person{Name: "Alice", Age: 25}
p.IncreaseAge()
fmt.Println("New Age:", p.Age)
}
Using a pointer receiver allows modifying the struct fields directly.
Anonymous Structs
Go also allows creating anonymous structs without defining a type.
package main
import "fmt"
func main() {
person := struct {
Name string
Age int
}{Name: "Alice", Age: 25}
fmt.Println(person)
}
This example defines and initializes an anonymous struct in a single step.
Conclusion
Structs in Go are powerful and allow defining custom data types. They enable object-oriented programming features such as encapsulation, methods, and pointers.
In the next lesson, we will explore Interfaces in Go, which provide a way to define behavior without specifying exact data types.