Golang : How to search a list of records or data structures
Got a newbie that asked me how to search a list of records(data structures) for specific item and below is a simple example on how to search or iterate a list of records using Golang.
What this simple program does is to demonstrate how to iterate through a list of records and look for a specific name that matches the search key. Once the record is found, return the record for further processing.
Here you go!
package main
import (
"fmt"
"strings"
)
type citySize struct {
Name string
Population float64
}
// cities with the largest population in the world
var citiesList = []citySize{
{"Tokyo", 38001000},
{"Delhi", 25703168},
{"Shanghai", 23740778},
{"Sao Paulo", 21066245},
}
func findRecordsByCityName(name string) bool {
for _, v := range citiesList {
// convert to lower case for exact matching
if strings.ToLower(v.Name) == strings.ToLower(name) {
return true
}
}
return false
}
func returnRecordsByCityName(name string) citySize {
for _, v := range citiesList {
// convert to lower case for exact matching
if strings.ToLower(v.Name) == strings.ToLower(name) {
return v
}
}
return citySize{"", 0}
}
func main() {
if !findRecordsByCityName("New York") {
fmt.Println("New York is not in the list!")
}
// Check if Tokyo is in the list
cityData := returnRecordsByCityName("Tokyo")
if cityData.Name != "" {
fmt.Println(cityData)
}
// Check if Teluk Intan is in the list
cityData = returnRecordsByCityName("Teluk Intan")
if cityData.Name != "" {
fmt.Println(cityData)
} else {
fmt.Println("Teluk Intan is not in the list")
}
}
Output:
New York is not in the list!
{Tokyo 3.8001e+07}
Teluk Intan is not in the list
Happy coding!
Reference:
https://www.socketloop.com/tutorials/golang-check-if-item-is-in-slice-array
See also : Golang : How to filter a map's elements for faster lookup
By Adam Ng(黃武俊)
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.5k Unix/Linux : How to test user agents blocked successfully ?
+5.8k Golang : Experimenting with the Rejang script
+7.3k Golang : Convert(cast) io.Reader type to string
+21.8k Golang : How to run Golang application such as web server in the background or as daemon?
+24.6k Golang : Create PDF file from HTML file
+16.8k Golang : Covert map/slice/array to JSON or XML format
+25.4k Golang : missing Mercurial command
+13k Golang : Date and Time formatting
+8.3k Golang : Another camera capture GUI application with GTK and OpenCV
+14.8k Golang : How do I get the local IP (non-loopback) address ?
+10k Golang : cannot assign type int to value (type uint8) in range error
+14.1k Golang : How to determine if user agent is a mobile device example