find the range of a list of numbers in go

To find the range of a list of numbers in Go, you can use a for loop to iterate through the list and keep track of the minimum and maximum values you encounter. Here's an example:

main.go
func findRange(nums []int) (int, int) {
    min := nums[0]
    max := nums[0]
    for _, num := range nums {
        if num < min {
            min = num
        }
        if num > max {
            max = num
        }
    }
    return min, max
}
247 chars
14 lines

In this function, we initialize min and max to the first value in the list. Then for each subsequent value in the list, we compare it to min and max and update their values if necessary. Finally, we return the minimum and maximum values as a tuple.

You can call this function with a slice of integers to find its range:

main.go
nums := []int{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}
min, max := findRange(nums)
fmt.Printf("Range: %d-%d\n", min, max)
114 chars
4 lines

This will output:

main.go
Range: 1-9
11 chars
2 lines

gistlibby LogSnag