To create and use a sorted index for ordered data retrieval in Go, you can use the sort
package and a custom data structure. Here's a step-by-step guide:
type Person struct {
Name string
Age int
}
sort.Interface
interface: To enable sorting on your data structure, you need to implement the required methods of the sort.Interface
interface. This includes Len()
, Less(i, j int) bool
, and Swap(i, j int)
.type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
sort.Sort()
function to sort the data based on your implementation of sort.Interface
.people := []Person{
{"Alice", 25},
{"Bob", 30},
{"Charlie", 20},
}
sort.Sort(ByAge(people))
sort.Search()
function.index := sort.Search(len(people), func(i int) bool { return people[i].Age >= 25 })
if index < len(people) && people[index].Age == 25 {
fmt.Println("Found:", people[index].Name)
} else {
fmt.Println("Not Found")
}
In the example above, the sort.Search()
function searches for the index of the first element that has an age greater than or equal to 25. If the element is found, it prints the corresponding person's name; otherwise, it prints "Not Found".
By following these steps, you can create and use a sorted index for ordered data retrieval in Go.