0
0
Goprogramming~10 mins

Accessing struct fields in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Accessing struct fields
Define struct type
Create struct variable
Access field using dot
Use or print field value
END
First, we define a struct type, then create a variable of that type. We access fields using the dot (.) operator and use the values.
Execution Sample
Go
package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{Name: "Alice", Age: 30}
    fmt.Println(p.Name)
}
This code defines a Person struct, creates a variable p, and prints the Name field.
Execution Table
StepActionVariable/FieldValueOutput
1Define struct type PersonPersonstruct with fields Name(string), Age(int)
2Create variable ppPerson{Name: "Alice", Age: 30}
3Access field p.Namep.Name"Alice"
4Print p.NameAlice
5End of program
💡 Program ends after printing the Name field value.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
pundefinedPerson{Name: "Alice", Age: 30}Person{Name: "Alice", Age: 30}Person{Name: "Alice", Age: 30}
p.Nameundefined"Alice""Alice""Alice"
p.Ageundefined303030
Key Moments - 2 Insights
Why do we use a dot (.) to access struct fields?
The dot operator connects the struct variable to its fields. For example, p.Name accesses the Name field inside p. See execution_table step 3.
Can we access a field before creating the struct variable?
No, the struct variable must exist first. In the table, p is created at step 2 before accessing p.Name at step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of p.Name at step 3?
A"30"
Bundefined
C"Alice"
DPerson struct
💡 Hint
Check the 'Value' column at step 3 in the execution_table.
At which step is the struct variable p created?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column in execution_table for variable creation.
If we change p.Name to "Bob", what will be printed at step 4?
A"Bob"
B"Alice"
C30
DError
💡 Hint
Refer to variable_tracker to see how changing p.Name affects output.
Concept Snapshot
Accessing struct fields in Go:
- Use dot (.) to get or set fields: variable.field
- Struct variable must be created before access
- Example: p.Name accesses Name field of p
- Fields hold values like strings or ints
- Use fmt.Println to display field values
Full Transcript
This visual trace shows how to access fields of a struct in Go. First, we define a struct type Person with fields Name and Age. Then we create a variable p of type Person with Name set to "Alice" and Age to 30. We access the Name field using p.Name and print it. The dot operator connects the variable to its fields. The variable tracker shows how p and its fields hold values during execution. The program ends after printing "Alice".