Managing User Data with Filtering and Aggregation in Go
Introduction
Welcome to today's lesson on applying data filtering and aggregation in a real-world scenario using a user management system in Go. We'll start by building a foundational structure that can handle basic user operations. Then, we'll expand it by introducing more advanced functionalities that allow filtering and aggregating user data.
Starter Task Methods
In our starter task, we will implement a set of functions that manage basic operations on a collection of user data, specifically handling adding new users, retrieving user profiles, and updating user profiles.
Here are the starter task methods:
addUser(userID string, age int, country string, subscribed bool) bool- Adds a new user with the specified attributes. The parameters are passed by value since you're providing complete new values for the addition, and there's no need to track changes after the function call. Returnstrueif the user was added successfully andfalseif a user with the sameuserIDalready exists.getUser(userID string) *UserProfile- Returns a pointer to the user's profile if the user exists; otherwise, returnsnil.updateUser(userID string, age *int, country *string, subscribed *bool) bool- Updates the user's profile based on non-nil parameters. Differently fromaddUser, notice the use of pointers which allows for selective updates; by passing anil, you indicate that a specific field should remain unchanged. Returnstrueif the user exists and was updated;falseotherwise.
To store the user data, we will define a UserProfile struct.
Starter Task Implementation
Here is the implementation of our starter task in Go:
The code provides a basic user management system in Go:
- It uses the
UserProfilestruct to store user details such as age, country, and subscription status. - The
UserManagerstruct manages user profiles in a map, with user IDs as keys. - The
NewUserManagerfunction initializesUserManagerwith an empty map of users. - Helper functions (
intPointer,stringPointer,boolPointer) are included to allow optional parameters to be easily passed when updating user profiles. - In the
mainfunction, users are added, retrieved, and updated to demonstrate the functionality of the user management system.
