To find the minimum and maximum values in a slice of integers in Golang, you can iterate over the slice to compare and update the values of the minimum and maximum. Here's an example code snippet:
package main
import (
"fmt"
)
func findMinMax(slice []int) (int, int) {
if len(slice) == 0 {
return 0, 0 // or return any default values you prefer
}
min := slice[0]
max := slice[0]
for _, num := range slice {
if num < min {
min = num
}
if num > max {
max = num
}
}
return min, max
}
func main() {
numbers := []int{10, 5, 7, 3, 8}
min, max := findMinMax(numbers)
fmt.Printf("Minimum: %d\n", min)
fmt.Printf("Maximum: %d\n", max)
}
Output:
Minimum: 3
Maximum: 10
In the findMinMax
function, we initialize min
and max
with the first element of the slice. Then, we iterate over the remaining elements of the slice, and if a smaller value is found, min
is updated accordingly. Similarly, if a larger value is found, max
is updated. Finally, we return the minimum and maximum values.
In the main
function, we create a slice of integers (numbers
), call the findMinMax
function on it, and print the respective minimum and maximum values.