Go Learning Notes - Part 2: Array, Slices, Loops & String Processing
Source: Dev.to
Arrays (Fixed Size Collections)
An array in Go has a fixed size.
var numbers [3]int = [3]int{10, 20, 30}
If I used an array for bookings, it would look like this:
var bookings [50]string
Limitations
- The size is fixed
- Harder to manage dynamic data
That’s why slices are usually preferred.
Slices (Dynamic Collections)
Instead of using a fixed array, I used a slice to store bookings:
bookings := []string{}
Every time a user books:
bookings = append(bookings, fName+" "+lName)
What I Learned
- Slices don’t have a fixed size
append()adds new elements- Slices are the most common way to manage lists in Go
Infinite Loop
I wrapped the booking logic inside an infinite loop:
for {
// booking logic here
}
Why use it?
- Allows multiple users to book tickets continuously
- The program keeps running until manually stopped
Looping with range (For‑Each)
To extract first names from all bookings:
for _, booking := range bookings {
name := strings.Fields(booking)
firstNames = append(firstNames, name[0])
}
What range Does
- Iterates over slices (and other collections)
- Returns both index and value (the index can be ignored)
- Makes looping clean and simple
Blank Identifier (_)
In the loop:
for _, booking := range bookings {
// ...
}
- The
_ignores the index value - Prevents “unused variable” errors
This is called the blank identifier in Go.
strings.Fields()
name := strings.Fields(booking)
What It Does
- Splits a string into a slice of words, using spaces as separators
Example
"Kervie Jay", "Kurt John"
Becomes:
[]string{"Kervie", "Jay"} // and []string{"Kurt", "John"}
Extracting the first name:
firstName := name[0]
Using uint
var remainingTickets uint = 50
var userTickets uint
What I Learned
uintis an unsigned integer (cannot be negative)- Ideal for values like ticket counts where negative numbers don’t make sense