Bird
Raised Fist0
Goprogramming~10 mins

Why structs are used in Go - Visual Breakdown

Choose your learning style10 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.

Practice

(1/5)
1. Why do Go programmers use structs in their code?
easy
A. To group related data together into one unit
B. To perform mathematical calculations faster
C. To create loops and control program flow
D. To handle errors automatically

Solution

  1. Step 1: Understand the purpose of structs

    Structs are used to combine multiple pieces of related data into a single unit, like grouping a person's name, age, and address together.
  2. Step 2: Compare options with struct purpose

    Only To group related data together into one unit describes grouping related data, which matches the purpose of structs. Other options describe unrelated tasks.
  3. Final Answer:

    To group related data together into one unit -> Option A
  4. Quick Check:

    Structs = Group related data [OK]
Hint: Structs bundle related info like a folder [OK]
Common Mistakes:
  • Thinking structs are for calculations
  • Confusing structs with loops
  • Assuming structs handle errors
2. Which of the following is the correct way to define a struct named Person with fields Name (string) and Age (int) in Go?
easy
A. struct Person { Name: string, Age: int }
B. type Person struct { Name string; Age int }
C. Person := struct(Name string, Age int)
D. class Person { Name string; Age int }

Solution

  1. Step 1: Recall Go struct syntax

    In Go, structs are defined using the keyword type followed by the struct name and the struct keyword with fields inside curly braces.
  2. Step 2: Check each option

    type Person struct { Name string; Age int } matches Go syntax exactly. Options A and C use incorrect syntax, and D uses 'class' which is not used in Go.
  3. Final Answer:

    type Person struct { Name string; Age int } -> Option B
  4. Quick Check:

    Go struct syntax = type Person struct { Name string; Age int } [OK]
Hint: Use 'type Name struct { fields }' to define structs [OK]
Common Mistakes:
  • Using 'class' instead of 'struct'
  • Incorrect field syntax with colons
  • Assigning struct with ':=' instead of type
3. What will be the output of this Go code?
package main
import "fmt"

type Book struct {
    Title string
    Pages int
}

func main() {
    b := Book{Title: "Go Basics", Pages: 150}
    fmt.Println(b.Title)
}
medium
A. {Go Basics 150}
B. 150
C. Go Basics
D. Compilation error

Solution

  1. Step 1: Understand struct initialization and field access

    The struct Book is created with Title "Go Basics" and Pages 150. Accessing b.Title prints the Title field.
  2. Step 2: Identify printed value

    The code prints only b.Title, so output is "Go Basics". Other options print Pages, whole struct, or error which do not match.
  3. Final Answer:

    Go Basics -> Option C
  4. Quick Check:

    Print struct field = Title value [OK]
Hint: Print struct.field to get that value [OK]
Common Mistakes:
  • Printing whole struct instead of field
  • Confusing field names
  • Expecting Pages to print
4. Identify the error in this Go code that uses a struct:
package main
import "fmt"

type Car struct {
    Brand string
    Year int
}

func main() {
    c := Car{Brand: "Toyota", Year: "2020"}
    fmt.Println(c)
}
medium
A. Year field has wrong data type
B. Missing semicolon after struct definition
C. Cannot print struct directly
D. Brand field name is invalid

Solution

  1. Step 1: Check struct field types and values

    The struct defines Year as int, but the code assigns a string "2020" to Year, causing a type mismatch.
  2. Step 2: Verify other options

    Go does not require semicolons after struct definitions, structs can be printed, and Brand is a valid field name.
  3. Final Answer:

    Year field has wrong data type -> Option A
  4. Quick Check:

    Field type mismatch = Year field has wrong data type [OK]
Hint: Match field types exactly when assigning values [OK]
Common Mistakes:
  • Assigning string to int field
  • Thinking semicolons are needed
  • Believing structs can't be printed
5. You want to store information about multiple students, each with a Name (string) and Grades (slice of int). Which approach best uses structs to organize this data?
hard
A. Store all names and grades in a single string separated by commas
B. Use two separate slices: one for names and one for grades, matching indexes
C. Create a map with student names as keys and grades as values
D. Create a struct Student with fields Name string and Grades []int, then make a slice of Student

Solution

  1. Step 1: Understand data grouping needs

    Each student has a name and multiple grades, so grouping these related data in one struct is clear and organized.
  2. Step 2: Evaluate options for clarity and maintainability

    Create a struct Student with fields Name string and Grades []int, then make a slice of Student uses a struct to group data and a slice to hold many students, which is clean and easy to manage. Other options separate data or mix types, making code harder to maintain.
  3. Final Answer:

    Create a struct Student with fields Name string and Grades []int, then make a slice of Student -> Option D
  4. Quick Check:

    Structs group related data + slice holds many [OK]
Hint: Use struct for one item, slice for many [OK]
Common Mistakes:
  • Using separate slices causing index errors
  • Storing data as plain strings
  • Using maps without struct grouping
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard