On Tue, Nov 5, 2019 at 12:30 PM toddsurfs via golang-nuts
<golang-nuts@googlegroups.com> wrote:
>
> Sorry if this question reveals my newness to Go. I tried searching the 
> mailing list but I couldn't find anything in a quick search. It seems like 
> many languages include the ability to check if an array, or slice contain a 
> particular value. I understand that you could do this easily with a for loop 
> or alternatively use a map instead. However, is there a reason why Go doesn't 
> just have slice.Contains(interface{}) or maybe a builtin contains(mySlice, 
> interface{}) ?
>
> I assume one reason might be because slices could potentially be really 
> large? Or maybe the community feels that a simple for loop is so easy that it 
> is not necessary? I would love to understand this more.

This is basically the generics question: why can't you write a generic
function that operates on slices independently of the type of the
slice element?  In the absence of generics, the function has to be
written using an empty interface, which provides no compile-time type
checking.  So people just write the loop.

Using the design draft at
https://go.googlesource.com/proposal/+/master/design/go2draft-contracts.md
this would be written as

func Contains(type T comparable)(s []T, x T) bool {
    for _, v := range s {
        if v == x {
            return true
        }
    }
    return false
}

Ian

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcUYKKFk-e1HqAAXkZz%2BBFYCHu67LnOYoRkFjF%3D%3D0mu4_A%40mail.gmail.com.

Reply via email to