Maps of Structs
Part of the Logic & Flow section of Coddy's GO journey — lesson 26 of 68.
Maps become incredibly powerful when you store structs as values. This pattern allows you to organize complex, structured data using meaningful keys for easy lookup and retrieval.
When you use structs as map values, you're essentially creating a collection where each key points to a complete data record. Here's how you declare and initialize such a map:
type Student struct {
ID int
Grade string
}
students := map[string]Student{
"Alice": {ID: 101, Grade: "A"},
"Bob": {ID: 102, Grade: "B"},
}You can access and work with the struct data through the map just like any other map operation. To get a student's information, you simply use their name as the key:
alice := students["Alice"]
fmt.Println(alice.ID) // prints: 101
fmt.Println(alice.Grade) // prints: AThis pattern is extremely common in Go applications for storing collections of related data, such as user profiles, product catalogs, or configuration settings where you need both structured data and fast key-based access.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a student grade management system using maps with structs as values. This challenge demonstrates how to organize complex student data using meaningful keys for efficient lookup and retrieval.
You will receive two inputs:
- A string representing the number of students (e.g.,
"4") - A string containing student data in the format:
"name1:id1:grade1,name2:id2:grade2,name3:id3:grade3"(e.g.,"Alice:101:A,Bob:102:B,Charlie:103:C,Diana:104:A")
Your task is to:
- Define a
Studentstruct with the following fields:ID(int) - the student's ID numberGrade(string) - the student's letter grade
- Create a map where the keys are student names (strings) and the values are
Studentstructs - Parse the student data from the second input:
- Split the input by commas to get individual student entries
- For each entry, split by colons to separate name, ID, and grade
- Convert the ID string to an integer
- Create a
Studentstruct and add it to the map with the name as the key
- Display all students in alphabetical order by name in the format:
"[name]: ID [id], Grade [grade]" - Calculate and display grade statistics:
- Count how many students have each grade (A, B, C, D, F)
- Display the count for each grade that appears in the format:
"Grade [grade]: [count] students" - Display grades in alphabetical order (A, B, C, D, F)
- Find and display the student with the highest ID in the format:
"Highest ID: [name] ([id])" - Display the total number of students:
"Total students: [count]"
Use the strconv package to convert the ID string to an integer, and the sort package to sort the student names alphabetically. This challenge demonstrates how maps with struct values provide an efficient way to organize and access complex data collections using meaningful identifiers.
Cheat sheet
Maps can store structs as values, creating collections where each key points to a complete data record:
type Student struct {
ID int
Grade string
}
students := map[string]Student{
"Alice": {ID: 101, Grade: "A"},
"Bob": {ID: 102, Grade: "B"},
}Access struct data through the map using the key:
alice := students["Alice"]
fmt.Println(alice.ID) // prints: 101
fmt.Println(alice.Grade) // prints: AThis pattern is commonly used for storing collections of related data like user profiles, product catalogs, or configuration settings where you need both structured data and fast key-based access.
Try it yourself
package main
import (
"fmt"
)
func main() {
// Read input
var numStudentsStr string
var studentData string
fmt.Scanln(&numStudentsStr)
fmt.Scanln(&studentData)
// TODO: Define Student struct here
// TODO: Create a map to store students (name as key, Student struct as value)
// TODO: Parse the student data and populate the map
// TODO: Display all students in alphabetical order by name
// TODO: Calculate and display grade statistics
// TODO: Find and display the student with the highest ID
// TODO: Display the total number of students
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors