Welcome to today's lesson! We'll explore a practical application of managing student enrollments for various courses using Go maps. Imagine you're operating an online course platform, and you need to efficiently handle enrollments, checks, and listings of students in different courses. Go maps are ideally suited for this problem due to their efficient lookups and storage operations. Furthermore, maps can emulate set behavior, helping us ensure that a student cannot enroll in a course more than once.
By the end of this session, you'll gain practical expertise in managing dynamic collection-like data with maps. Let’s dive in!
Here are the methods we need to implement in our enrollment system:
func (es *EnrollmentSystem) enroll(student string, course string): This method adds a student to a course. If the student is already enrolled, it does nothing, effectively behaving like a set addition.func (es *EnrollmentSystem) unenroll(student string, course string) bool: This method removes a student from a course. It returnstrueif the student was enrolled and is now removed. Otherwise, it returnsfalse. If, after unenrolling the student, the course becomes empty, the course is removed from the system.func (es *EnrollmentSystem) isEnrolled(student string, course string) bool: This method checks if a student is currently enrolled in a given course. It returnstrueif the student is enrolled, andfalseotherwise.func (es *EnrollmentSystem) listStudents(course string) []string: This method returns a list of all students enrolled in a specific course. It returns an empty slice if no students are enrolled.
Let's look at how to implement each of these methods step-by-step.
To start, we'll define our struct and gradually add each method.
First, we define our EnrollmentSystem struct:
In this code, we initialize an EnrollmentSystem struct with an enrollments map, mapping courses to sets of students. Let's take a deeper look at the type map[string]map[string]struct{}, employed by enrollments:
- Outer map: Maps
coursestrings to a corresponding inner map. The key is the course name. - Inner map: Emulates a student set for each course. The keys are the student names, and the values are of type
struct{}, which is a zero-size type in Go—perfect for set-like behavior without any additional overhead.
