Checking for a string in string slice

Hello all,

I’m trying to know if there is a builtin query to know if a string exists in a slice. Or should we always iterate over the slice to find that out ?

package main

import "fmt"

func main() {
    str := []string{"ak", "blr", "udp"}
   for _, num := range str {
        fmt.Println("str:", num)
   fmt.Println(str[2])   // This will give me 'udp', any alternate to this

How would i know if string ‘udp’ exists in the slice without iterating ?

You iterate to find out. If you need to do multiple fast lookups you can build a map. For large sets of strings you can sort and use binary search.

1 Like

Yeah, i understand it works gracefully with maps. I have a function that returns a []string, which should not have a very large set of data but there will be frequent query to it. So creating a map and moving this string slice there is what i’m left with then.

It doesn’t really matter if there were a built in or not for this - the amount of work to do per lookup is still the same. But if you are doing frequent queries on the same string slice, building a map once and for all is probably a win. Or maybe it’s better to sort and search. Benchmark if this is a hotspot in your program.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.