Arrays and Slices in Go: Add, Delete, Search, Update, Sort, and Filter
Go arrays and slices are straightforward once you understand their different roles. Arrays have a fixed length that is part of their type, while slices are flexible views over an underlying array and are the collection type used most often in application code.
The following examples use a slice of structs:
type Person struct {
Name string
Age int
}
people := []Person{
{Name: "Alice", Age: 30},
{Name: "Bob", Age: 25},
{Name: "John", Age: 20},
{Name: "Zara", Age: 35},
}1. Add an Element
Use append:
people = append(people, Person{Name: "Eve", Age: 28})append may reuse the existing backing array or allocate a new one, so assign the returned slice back to the variable.
2. Delete an Element
To remove the first matching person while preserving order:
func deletePerson(people []Person, name string) []Person {
for i, p := range people {
if p.Name == name {
return append(people[:i], people[i+1:]...)
}
}
return people
}
people = deletePerson(people, "Bob")This modifies the logical slice length and may reuse the same backing array. If removed values contain large referenced objects and the slice is long-lived, consider clearing the removed slot to help garbage collection.
3. Search for an Element
func searchByName(people []Person, name string) (Person, bool) {
for _, p := range people {
if p.Name == name {
return p, true
}
}
return Person{}, false
}
person, found := searchByName(people, "John")The boolean makes it possible to distinguish a successful lookup from the zero value of Person.
4. Update an Element
func updateAge(people []Person, name string, newAge int) bool {
for i := range people {
if people[i].Name == name {
people[i].Age = newAge
return true
}
}
return false
}
updated := updateAge(people, "Alice", 31)Because a slice references its backing array, changing people[i] updates the underlying element. Returning a boolean communicates whether a matching record was found.
5. Sort the Slice
With Go’s sort package, sort in ascending order by age:
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age
})Descending order:
sort.Slice(people, func(i, j int) bool {
return people[i].Age > people[j].Age
})In modern Go versions, slices.SortFunc is another option when you want a generic sorting API.
6. Filter Elements
func filterByAge(people []Person, ageLimit int) []Person {
result := make([]Person, 0, len(people))
for _, p := range people {
if p.Age > ageLimit {
result = append(result, p)
}
}
return result
}
filtered := filterByAge(people, 25)Preallocating capacity can reduce allocations when many items are expected to pass the filter.
Conclusion
Slices make common collection operations in Go explicit: append new values, search with loops, update by index, remove by reslicing, sort with comparison functions, and filter into a new slice. These small patterns cover a large share of everyday in-memory data manipulation in Go programs.