How to determine if a value is included in an array in Golang?
In Golang, to determine if an array contains a specific value, you can use a loop to iterate through the array, compare each element with the target value, and return true if a match is found, otherwise return false. Here is an example code:
package main
import "fmt"
func contains(arr []int, target int) bool {
for _, value := range arr {
if value == target {
return true
}
}
return false
}
func main() {
arr := []int{1, 2, 3, 4, 5}
target := 3
result := contains(arr, target)
fmt.Println(result)
}
In the example code above, the contains function takes an array of type int called arr and a target value called target. It iterates through the array using a for loop, comparing each element with the target value. If a matching value is found, it returns true; otherwise, it returns false.
In the main function, an array named arr and a target value named target are defined. The contains function is then called to check if the array arr contains the target value. Finally, the result is printed out.