Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Find element in array or slice

package main

import (
	"fmt"
)

func main() {
	celestialObjects := []string{"Moon", "Gas", "Asteroid", "Dwarf", "Asteroid", "Moon", "Asteroid"}
	fmt.Println(celestialObjects)
	var location int
	var found bool
	var str string

	str = "Asteroid"
	location, found = findElement(str, celestialObjects)
	if found {
		fmt.Printf("Found %v in %v\n", str, location)
	} else {
		fmt.Printf("Not found %v in %v\n", str, location)
	}

	str = "Star"
	location, found = findElement(str, celestialObjects)
	if found {
		fmt.Printf("Found %v in %v\n", str, location)
	} else {
		fmt.Printf("Not found %v in %v\n", str, location)
	}

}

func findElement(elem string, elements []string) (int, bool) {
	for i, value := range elements {
		if value == elem {
			return i, true
		}
	}
	return -1, false
}
[Moon Gas Asteroid Dwarf Asteroid Moon Asteroid]
Found Asteroid in 2
Not found Star in -1