find the sum of a list of numbers in go

To find the sum of a list of numbers in Go, we can create a function that takes in a slice of integers and returns the sum. Here's an example:

main.go
package main

import "fmt"

func sum(numbers []int) int {
    total := 0
    for _, number := range numbers {
        total += number
    }
    return total
}

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    fmt.Println(sum(numbers))
}
242 chars
17 lines

In this example, we define a function named sum that takes in a slice of integers named numbers. We then declare a variable named total and initialize it to 0. Next, we iterate over each element in the numbers slice using a for loop and add each element to the total variable. Finally, we return the total variable.

In the main function, we create a slice of integers named numbers and pass it to the sum function. We then use fmt.Println to print the sum of the numbers in the numbers slice, which is 15 in this case.

related categories

gistlibby LogSnag