DEV Community

Kervie Sazon
Kervie Sazon

Posted on

Go Learning Notes - Part 7: Struct

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
}
Enter fullscreen mode Exit fullscreen mode

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 {
    ...
}
Enter fullscreen mode Exit fullscreen mode

This means:

  • I created a new type called UserData
  • It has fields like firstName, lastName, email, and numberOfTickets
  • 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,
}
Enter fullscreen mode Exit fullscreen mode

Then I store it in a slice:

bookings = append(bookings, userData)
Enter fullscreen mode Exit fullscreen mode

Now instead a slice of maps, I use:

bookings = make([]UserData, 0)
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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)