Today I learned about Maps in Go and how to properly handle type conversion using the strconv package.
Maps in Go
I improved my booking app by replacing simple slices with maps to store structured user data.
Instead of storing only names like this:
bookings := []string{}
I now use a slice of maps:
bookings := make([]maps[string]string, 0)
Each user booking is stored as a map:
userData := make([]map[string]string)
userData["firstName"] = fName
userData["lastName"] = lName
userData["email"] = email
This makes the data more organized, easier to access and more scalable for real-world applications.
Now I can easily access specific values like:
bookings["firsName"]
Type Conversion in Go (strconv)
In my app, userTickets is a uint, but maps store values as string.
So I needed to convert the number into a string before storing it.
Solution: strconv.FormatUint()
userData["numberOfTickets"] = strconv.FormatUint(uint64(userTickeets), 10)
What’s happening here?
-
uint64(userTickets)- Convertuinttouint64 -
10- Base 10 (decimal) - Returns a
string
Now the ticket number can safely be stored inside the map.
For Better Understanding
Slice of Maps Declaration
var (
bookings = make([]map[string]string, 0)
)
Creating and Storing User Data in a Map
func bookTicket(userTickets uint, fName string, lName string, email string) {
RemainingTickets = RemainingTickets - userTickets
// create a map for a user
userData := make(map[string]string)
userData["firstName"] = fName
userData["lastName"] = lName
userData["email"] = email
userData["numberOfTickets"] = strconv.FormatUint(uint64(userTickets), 10)
bookings = append(bookings, userData)
}
Accessing Map Values Inside a Loop
func getFNames() []string {
firstNames := []string{}
for _, booking := range bookings {
firstNames = append(firstNames, booking["firstName"])
}
return firstNames
}
Import for Type Conversion
import "strconv"
This lesson made my booking application more structured and closer to real-world development.
Using maps helped me understand how Go handles data organization, and learning strconv improved my understanding of Go’s strict type system.
In summary, I learned how to use maps in Go to store structured user data more efficiently by creating a slice of map[string]string. I understood how to access specific values from a map while looping through the slice, such as retrieving all first names. I also learned that Go is strongly typed and requires explicit type conversion when working with different data types. Using strconv.FormatUint() helped me convert a uint value into a string so it can be stored properly inside a map.
Top comments (0)