Say I have a struct
type heights struct {
name string
height int // in inches
}
So let’s say I have 4 instances, where “Jim” is 72 inches, “Mary” is 61 inches, “Alex” is 69 inches, and “Ann” is 58 inches.
How do I do 2 queries: 1. Who is 61 inches high? 2. How tall is Ann? This seems to explained nowhere in all of the tutorials I have seen.
It is better idea if you put those “objects” in a slice and then do the search in that slice. For example
package main
import "fmt"
type Person struct {
name string
height int // in inches
}
func index(persons []Person, fn func(p Person) bool) int {
for i, p := range persons {
if fn(p) {
return i
}
}
return -1
}
func main() {
persons := []Person{
Person{name: "Jim", height: 72},
Person{name: "Mary", height: 61},
Person{name: "Alex", height: 69},
Person{name: "Ann", height: 58},
}
// Who is 61 inches high
pos := index(persons, func(p Person) bool {
return p.height == 61
})
if pos != -1 {
fmt.Println(persons[pos])
} else {
fmt.Println("Nobody is 61 inches tall")
}
// How tall is Ann
pos = index(persons, func(p Person) bool {
return p.name == "Ann"
})
if pos != -1 {
fmt.Println(persons[pos])
} else {
fmt.Println("Ann is not register")
}
}
1 Like
What @Yamil_Bracho proposed works but, depending on your needs you might need to do something more complex.
For instance if you have a huge number of items in the list you might have performances issue iterating on the whole slice. in this case you would need to use more complex data structure like maps.
Another problem in the provided solution is that it doesn’t work if you have multiple items with the same height.
Something a bit better would be could be
func indexes(persons []Person, fn func(p Person) bool) []int {
results := make([]int, 0)
for i, p := range persons {
if fn(p) {
results = append(results, i)
}
}
return results
}
Maybe you could use a package dedicated to collections: