英文:
Compare a string against a struct field within a slice of structs (sort.Search golang)
问题
type user struct {
name string
age int
}
data := []user{
{
name: "timothy",
age: 23,
},
{
name: "johnson",
age: 45,
},
{
name: "jason",
age: 44,
},
{
name: "handson",
age: 15,
},
{
name: "andrew",
age: 41,
},
}
fmt.Println(data)
val := "johnson"
found := false
i := sort.Search(len(data), func(i int) bool {
println(i)
return data[i].name == val
})
if i < len(data) && data[i].name == val {
found = true
}
fmt.Println(val, found)
我尝试在包含一些字符串字段的结构体数组中搜索字符串,但无法找到匹配项,例如使用johnson或andrew。问题出在哪里?谢谢!
英文:
type user struct {
name string
age int
}
data := []user{
{
name: "timothy",
age: 23,
},
{
name: "johnson",
age: 45,
},
{
name: "jason",
age: 44,
},
{
name: "handson",
age: 15,
},
{
name: "andrew",
age: 41,
},
}
fmt.Println(data)
val := "johnson"
found := false
i := sort.Search(len(data), func(i int) bool {
println(i)
return data[i].name == val
})
if i < len(data) && data[i].name == val {
found = true
}
fmt.Println(val, found)
I tried to search for a string within an array of structs that including some string fields, but couldn't get a match, for example using johnson or andrew. What is the problem? Thank you!
答案1
得分: 4
这将数据排序,然后对其进行搜索。
我不得不声明一个类型为users的切片,然后为users类型实现Len/Cmp/Swap方法。
sort.Search函数使用>=。
package main
import (
"fmt"
"sort"
)
type user struct {
name string
age int
}
type users []user
func (o users) Len() int { return len(o) }
func (o users) Less(i, j int) bool { return o[i].name < o[j].name }
func (o users) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
func main() {
data := users{
{
name: "timothy",
age: 23,
},
{
name: "johnson",
age: 45,
},
{
name: "jason",
age: 44,
},
{
name: "handson",
age: 15,
},
{
name: "andrew",
age: 41,
},
}
sort.Sort(data)
fmt.Println(data)
val := "johnson"
found := false
i := sort.Search(len(data), func(i int) bool {
println(i)
return data[i].name >= val
})
if i < len(data) && data[i].name == val {
found = true
}
fmt.Println(val, found)
return
}
英文:
This sorts the data into order, then does a search on it.
I had to declare a type users which is an slice of user,
then implement Len/Cmp/Swap for users type
The sort.Search function uses >=
package main
import (
"fmt"
"sort"
)
type user struct {
name string
age int
}
type users []user
func (o users) Len() int { return len(o) }
func (o users) Less(i, j int) bool { return o[i].name < o[j].name }
func (o users) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
func main() {
data := users{
{
name: "timothy",
age: 23,
},
{
name: "johnson",
age: 45,
},
{
name: "jason",
age: 44,
},
{
name: "handson",
age: 15,
},
{
name: "andrew",
age: 41,
},
}
sort.Sort(data)
fmt.Println(data)
val := "johnson"
found := false
i := sort.Search(len(data), func(i int) bool {
println(i)
return data[i].name >= val
})
if i < len(data) && data[i].name == val {
found = true
}
fmt.Println(val, found)
return
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论