Introduction
Structs help group related data together. Creating struct values lets you store and use this grouped data easily.
Structs help group related data together. Creating struct values lets you store and use this grouped data easily.
type StructName struct {
Field1 FieldType1
Field2 FieldType2
// ... more fields
}
// Creating a struct value
varName := StructName{
Field1: value1,
Field2: value2,
}Use the field names when creating struct values to avoid confusion.
You can also create struct values without field names, but it's less clear.
type Person struct {
Name string
Age int
}
p := Person{
Name: "Alice",
Age: 30,
}type Point struct {
X int
Y int
}
p := Point{10, 20}var p Person p.Name = "Bob" p.Age = 25
This program creates a Car struct value and prints its fields.
package main import "fmt" type Car struct { Brand string Year int } func main() { myCar := Car{ Brand: "Toyota", Year: 2022, } fmt.Println("My car brand is", myCar.Brand) fmt.Println("It was made in", myCar.Year) }
Always use field names when creating struct values for better clarity.
Struct fields can be accessed and changed using dot notation.
Structs group related data into one unit.
Create struct values using field names for clarity.
You can set or change fields after creating the struct.
Name as "Alice" and Age as 30 in Go?type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Bob", Age: 25}
p.Age = 26
fmt.Println(p)
}type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Eve", Age: "30"}
fmt.Println(p)
}Pass the test and this pattern moves unknown