Introduction to Structs
Start with Introduction to Structs
A struct collects related fields into a single named value, making it easier to represent a person, product or measurement.
What you’ll learn
- Explain the main purpose of introduction to structs.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Declare a struct with type Student struct { Name string; Score int } (normally one field declaration per line). A struct type describes the data shape; a struct value contains the actual fields.
Structs are values: assigning an ordinary struct to another variable copies its fields. A pointer to a struct instead refers to the same struct object. This distinction becomes important for methods.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
type Student struct {
Name string
Score int
}
func main() {
student := Student{Name: "Maya", Score: 90}
fmt.Println(student.Name, student.Score)
other := student
other.Score = 100
fmt.Println("Original:", student.Score)
fmt.Println("Copy:", other.Score)
}
Output
Maya 90
Original: 90
Copy: 100Trace what the program does
The literal makes one Student. The assignment to other copies that struct value, so changing other.Score does not change student.Score.
Avoid common mistakes
- A struct variable does not automatically refer to another struct variable after assignment.
- Field names and types form part of the struct declaration.
Try it yourself
Define a Book struct with Title and Pages, make a value, copy it and compare the values after changing one copy.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Introduction to Structs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.