JIA
JIA

Reputation: 173

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)

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!

Upvotes: 0

Views: 721

Answers (1)

Vorsprung
Vorsprung

Reputation: 34317

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
}

Upvotes: 4

Related Questions