Structs are a composite type that allow you to encapsulate different values together into a single unit. Think of them as a way to group related data together.
type Person struct {
Name string
Age int
City string
}
A struct is defined using the type keyword followed by the struct name and the struct keyword. Inside the curly braces, you define the fields (properties) that the struct will contain, each with its own type.
// Create a struct instance
var john Person
john.Name = "John"
john.Age = 30
john.City = "New York"
// Or initialize with values
alice := Person{
Name: "Alice",
Age: 25,
City: "Los Angeles",
}
// You can also initialize without field names (order matters)
bob := Person{"Bob", 35, "Chicago"}
Structs allow you to group related data together, making your code more organized and easier to understand. They're particularly useful when you need to pass multiple related values around your program.
// Accessing struct fields
fmt.Println(alice.Name) // Prints: Alice
fmt.Println(alice.Age) // Prints: 25
// Modifying struct fields
alice.City = "San Francisco"
fmt.Println(alice.City) // Prints: San Francisco
Structs are essential for modeling real-world entities in your code. Instead of managing separate variables for each property, you can group them into a logical unit.
type Product struct {
ID int
Name string
Price float64
}
// Much cleaner than:
// productID := 1
// productName := "Laptop"
// productPrice := 999.99
laptop := Product{
ID: 1,
Name: "Laptop",
Price: 999.99,
}
For this challenge, create a struct called Character that represents a video game character with the following fields:
Name (string)Health (int)PowerLevel (uint)IsAlive (bool)Then create two instances of this struct:
goku character instance named "Goku" with 100 health, 9001 power level, and is alive,frieza character instance named "Frieza" with 80 health, 8500 power level, and is alivePrint out:
Name and PowerLevel on the same lineIsAlive on a new line