This function's objective is very simple. It takes array
and checks if val
is a value inside of this array. It returns whether val
exists and which is the index inside the array that contains val
.
Could this be coded in a better way? How would I implement this to work with any kind of array (the code below works only with arrays of strings)?
package main
import "fmt"
func in_array(val string, array []string) (exists bool, index int) {
exists = false
index = -1;
for i, v := range array {
if val == v {
index = i
exists = true
return
}
}
return
}
func main() {
names := []string{ "Mary", "Anna", "Beth", "Johnny", "Beth" }
fmt.Println( in_array("Jack", names) )
}
Go probably provides a similar function, but this is for study purposes only.
ok bool
anderr error
are usually the second parameter. See e.g.val, exists := mymap[key]
. – Arne Aug 21 at 14:02