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,913 questions

51,846 answers

573 users

How to check if element exists in an array with Go

2 Answers

0 votes
package main

import (
	"fmt"
	"reflect"
)

func main() {
	arr := [5]string{"go", "java", "php", "python", "c++"}

	fmt.Println(elementExists(arr, "go"))
	fmt.Println(elementExists(arr, "c"))
	fmt.Println(elementExists(arr, 12))
}

func elementExists(arrayType interface{}, element interface{}) bool {
	arr := reflect.ValueOf(arrayType)

	for i := 0; i < arr.Len(); i++ {
		if arr.Index(i).Interface() == element {
			return true
		}
	}

	return false
}
   

   
/*
run:
   
true
false
false
 
*/

 



answered Aug 10, 2020 by avibootz
0 votes
package main

import (
	"fmt"
)

func main() {
	arr := [5]string{"go", "java", "php", "python", "c++"}

	fmt.Println(elementExists(arr, "go"))
	fmt.Println(elementExists(arr, "c"))
	fmt.Println(elementExists(arr, "php"))
}

func elementExists(arr [5]string, s string) bool {
   for _, element := range arr {
      if element == s {
         return true
      }
   }
   return false
}
   
   
   
/*
run:
   
true
false
true
 
*/

 



answered Aug 10, 2020 by avibootz
...