Generic Structs
Start with Generic Structs
Generic structs can model pairs, containers and records while keeping their field types explicit.
What you’ll learn
- Explain the main purpose of generic structs.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A struct may have several independent type parameters: type Pair[A, B any] struct { First A; Second B }. The two fields need not share the same type. When constructing a generic literal, specify type arguments in its type name.
Generic structs make sense when code works with the container shape regardless of the chosen types. Consider a normal concrete struct when it describes a domain record with fixed fields.
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 Pair[A, B any] struct {
First A
Second B
}
func main() {
student := Pair[string, int]{First: "Noah", Second: 91}
coordinate := Pair[float64, float64]{First: 2.5, Second: 4.0}
fmt.Println("Student:", student.First, student.Second)
fmt.Println("Coordinate:", coordinate.First, coordinate.Second)
}
Output
Student: Noah 91
Coordinate: 2.5 4Trace what the program does
Pair is instantiated with a string/int combination for the student and two float64 fields for the coordinate. Field accesses preserve their declared types.
Avoid common mistakes
- The type argument list is part of the instantiated type, not optional decoration.
- Different type parameters are not automatically convertible to one another.
Try it yourself
Add a generic Triple[A, B, C] struct and make one value holding a string, an int, and a bool.
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 Generic 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.