0
0
Goprogramming~10 mins

Why structs are used in Go - Visual Breakdown

Choose your learning style9 modes available
Concept Flow - Why structs are used
Define struct type
Create struct variable
Assign values to fields
Use struct fields
Access or modify data
Pass struct to functions
Organize related data together
Simplify code and improve clarity
Structs group related data into one unit, making code clearer and easier to manage.
Execution Sample
Go
package main
import "fmt"

type Person struct {
  Name string
  Age  int
}

func main() {
  p := Person{Name: "Anna", Age: 30}
  fmt.Println(p.Name, p.Age)
}
This code creates a Person struct, assigns values, and prints the fields.
Execution Table
StepActionEvaluationResult
1Define struct type PersonPerson has fields Name (string), Age (int)Struct type ready
2Create variable p of type Personp is empty structp initialized with zero values ("", 0)
3Assign Name="Anna", Age=30 to pp.Name = "Anna", p.Age = 30p now holds {Name: "Anna", Age: 30}
4Print p.Name and p.AgeOutput valuesAnna 30
5End of programNo more actionsProgram stops
💡 Program ends after printing struct field values
Variable Tracker
VariableStartAfter Step 2After Step 3Final
pundefined{Name: "", Age: 0}{Name: "Anna", Age: 30}{Name: "Anna", Age: 30}
Key Moments - 2 Insights
Why do we use structs instead of separate variables?
Structs group related data together, making it easier to manage and pass around, as shown in step 3 and 4 of the execution_table.
What happens if we don't assign values to struct fields?
Fields get default zero values (empty string for Name, 0 for Age), as seen in step 2 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of p after step 2?
Aundefined
B{Name: "", Age: 0}
C{Name: "Anna", Age: 30}
Dnil
💡 Hint
Check the 'After Step 2' column in variable_tracker for variable p
At which step does p get the Name "Anna" assigned?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' and 'Result' columns in execution_table rows
If we did not assign Age, what would be printed for p.Age?
A0
B30
Cnil
Dundefined
💡 Hint
Refer to step 2 in execution_table where default zero values are shown
Concept Snapshot
Structs group related data fields into one unit.
Define with type and fields.
Create variables to hold data.
Assign and access fields with dot notation.
Helps organize and simplify code.
Full Transcript
Structs in Go are used to group related data together. First, you define a struct type with named fields. Then you create a variable of that struct type. Initially, fields have zero values like empty strings or zero numbers. You assign values to the fields using the dot notation. Finally, you can use these fields in your program, for example, printing them. Structs make your code clearer by keeping related information together instead of using separate variables.