Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: strings: add ListIndex #16774

Closed
256dpi opened this issue Aug 17, 2016 · 3 comments
Closed

proposal: strings: add ListIndex #16774

256dpi opened this issue Aug 17, 2016 · 3 comments

Comments

@256dpi
Copy link

256dpi commented Aug 17, 2016

While reading the source code of many packages lately I stumbled a lot over the following function declaration:

func stringInList(list []string, str string) bool {
    for _, val := range list {
        if val == str {
            return true
        }
    }

    return false
}

I have the feeling that searching a slice of strings for the first occurrence of a string is a very common need and might be a good addition to the standard library.

I would propose the following function for the strings package:

func ListIndex(list []string, str string) int {
    for i, val := range list {
        if val == str {
            return i
        }
    }

    return -1
}

I know adding stuff to the standard library is a big thing, but I had to give it a least a try. ;)

@Ganners
Copy link

Ganners commented Aug 17, 2016

If you're happy for your list of strings to be sorted, then this essentially exists as sort.SearchStrings: https://golang.org/pkg/sort/#SearchStrings

The linear search listed above is so trivial in implementation that I wouldn't think it's worth adding, binary search is far superior if you can afford the sort.

@griesemer
Copy link
Contributor

Adding this would set a precedent for many other little "useful" utility functions that are trivial to write. Where does it end? I'm against adding things like this to the std lib.

@256dpi
Copy link
Author

256dpi commented Aug 17, 2016

@Ganners I wasn't aware of sort.SearchStrings existence... Thanks for pointing it out. You're right, a binary search would be a better choice.

@griesemer: I wouldn't ask for a Max(ints []int) int function, but as there is already a package with string utility functions in place, I thought it would be a nice addition. I scrolled multiple times through the package to check if there is really no such function already there. ;)

@256dpi 256dpi closed this as completed Aug 17, 2016
@golang golang locked and limited conversation to collaborators Aug 17, 2017
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants