Concept Flow - Creating struct values
Define struct type
Create struct value
Assign values to fields
Use struct value in code
End
This flow shows how to define a struct type, create a struct value, assign values to its fields, and then use it.
package main import "fmt" type Person struct { Name string Age int } func main() { p := Person{Name: "Alice", Age: 30} fmt.Println(p) }
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Define struct type Person | Person struct with fields Name(string), Age(int) | Type Person created |
| 2 | Create struct value p with Name="Alice", Age=30 | Person{Name: "Alice", Age: 30} | p holds {Name: "Alice", Age: 30} |
| 3 | Print struct value p | fmt.Println(p) | {Alice 30} printed to console |
| 4 | End of execution | - | Program ends |
| Variable | Start | After Step 2 | Final |
|---|---|---|---|
| p | undefined | {Name: "Alice", Age: 30} | {Name: "Alice", Age: 30} |
Creating struct values in Go:
- Define struct type with fields
- Create value using TypeName{Field1: val1, Field2: val2}
- Field names clarify assignments
- Values can be printed or used
- Omitting field names requires exact orderName 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