Today I learned about Structs in Go and encountered the type keyword, which allows us to create custom data types. This lesson helped me improve my booking app by replacing maps with a more structured and type-safe approach.
Struct
A struct is a composite data type that groups together variables under a single name. It helps organize related data into one logical unit.
In my booking app, instead of using a map[string]string, I created a custom struct:
type UserData struct {
firstName string
lastName string
email string
numberOfTickets uint
}
Here, UserData is a custom type created using the type keyword.
The type Keyword
The type keyword in Go allows us to define our own data types.
type UserData struct {
...
}
This means:
- I created a new type called
UserData - It has fields like
firstName,lastName,email, andnumberOfTickets - It behaves like a blueprint for user booking information
This makes the program cleaner and more structured.
Creating a struct Instance
Inside my bookTicket() function, I create a new struct instance like this:
userData := UserData{
firstName: fName,
lastName: lName,
email: email,
numberOfTickets: userTickets,
}
Then I store it in a slice:
bookings = append(bookings, userData)
Now instead a slice of maps, I use:
bookings = make([]UserData, 0)
This is much more readable and type-safe.
Accessing Struct Fields
To get all first names, I loop through the slice and access struct fields using dot(.) notation:
for _, booking := range bookings {
firstNames = append(firstNames, booking.firstName)
}
Unlike maps, struct fields are accessed using . instead of ["key"].
In summary, I learned how to use structs in Go to group related data into a single, organized unit. I understood that the type keyword allows me to create custom data types like UserData, which act as blueprints for structured information. I also learned how to create struct instances and access their fields using dot notation.
Top comments (0)