Working with Arrays in Go: Adding, Deleting, Searching, Updating, sorting and Filtering Elements
In Go, working with arrays and slices of structs is a fundamental skill that can be applied across various applications. This guide demonstrates how to perform common operations on an array of structs. We will cover adding, deleting, searching, updating, sorting, and filtering elements using a Person
struct as our example.
Struct Definition
First, define the Person
struct that will hold the data:
type Person struct {
Name string
Age int
}
Here’s our initial array of people:
people := []Person{
{"Alice", 30},
{"Bob", 25},
{"John", 20},
{"Zara", 35},
}
1. Adding an Element to the Array
To add a new element to the array, we use the append
function:
func addPerson(people []Person, newPerson Person) []Person {
return append(people, newPerson)
}
// Example usage:
person := addPerson(people, Person{"Eve", 28})
fmt.Print(person)
This function appends a new Person
to the existing array.
2. Deleting an Element from the Array
To delete an element from the array, you need to remove the element at the specified name:
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
}
// Example usage:
person := deletePerson(people, "Bob")
fmt.Print(person) // Deletes "Bob"
This function removes the element at the specified index.
3. Searching for an Element by Name
To find a person by name, we iterate over the array and return the matching element:
func searchByName(people []Person, name string) (Person, bool) {
for _, person := range people {
if person.Name == name {
return person, true
}
}
return Person{}, false
}
// Example usage:
person, found := searchByName(people, "John")
if found {
fmt.Println("Found:", person)
} else {
fmt.Println("Not found")
}
This function returns the Person
and a boolean indicating whether the person was found.
4. Updating an Element
To update a person’s age, we locate the person by name and modify their age:
func updateAge(people []Person, name string, newAge int) []Person {
for i, person := range people {
if person.Name == name {
people[i].Age = newAge
break
}
}
return people
}
// Example usage:
person := updateAge(people, "Alice", 31)
fmt.Print(person)
This function updates the age of the specified person.
5. Sorting the Array
Sorting the array by age can be done in either ascending or descending order using sort.Slice
:
Ascending Order:
func sortByAgeAscending(people []Person) []Person {
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age
})
return people
}
// Example usage:
person := sortByAgeAscending(people)
fmt.Print(person)
Descending Order:
func sortByAgeDescending(people []Person) []Person {
sort.Slice(people, func(i, j int) bool {
return people[i].Age > people[j].Age
})
return people
}
// Example usage:
person := sortByAgeAscending(people)
fmt.Print(person)
These functions sort the array based on the Age
field.
6. Filtering by a Condition
To filter the array based on a condition, such as age greater than a specified value:
func filterByAge(people []Person, ageLimit int) []Person {
var result []Person
for _, person := range people {
if person.Age > ageLimit {
result = append(result, person)
}
}
return result
}
// Example usage:
filteredPeople := filterByAge(people, 25)
fmt.Println("People with age > 25:", filteredPeople)
This function returns a new array containing only those persons who meet the condition.
Conclusion
Managing arrays of structs in Go is straightforward with these fundamental operations. By leveraging functions like addPerson
, deletePerson
, searchByName
, updateAge
, sortByAgeAscending
, sortByAgeDescending
, and filterByAge
, you can efficiently manipulate data within your applications. Each of these operations forms a building block for more complex data management tasks in Go.