Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,914 questions

51,847 answers

573 users

How to check if element exists in a slice with Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func main() {

    arr := []string{"go", "c++", "php", "python"}

    _, found := Find(arr, "abc")
    if !found {
        fmt.Println("not found")
    }

    i, found := Find(arr, "php")
    if !found {
        fmt.Println("not found")
    }
    fmt.Printf("found at index: %d\n", i)
}

func Find(slice []string, val string) (int, bool) {
    for i, item := range slice {
        if item == val {
            return i, true
        }
    }
    return -1, false
}
 
 
/*
run:
 
not found
found at index: 2
 
*/

 



answered Aug 7, 2020 by avibootz
...