Golang : Totalize or add-up an array or slice example
A simple example on how to totalize or add-up all the integer elements in a slice/array. Just use a for
loop to add up the elements one-by-one.
Here you go!
package main
import (
"fmt"
)
func main() {
slice := []int{1, 2, 3, 4, 5, 6}
total := 0
for i := 0; i < len(slice); i++ {
total = total + slice[i]
}
fmt.Println("Slice elements are : ", slice)
fmt.Println("Elements add up to : ", total)
}
Sample output:
Slice elements are : [1 2 3 4 5 6]
Elements add up to : 21
See also : Golang : 2 dimensional array example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.5k Golang : Convert(cast) io.Reader type to string
+12.2k Golang : reCAPTCHA example
+4.6k Golang : What is StructTag and how to get StructTag's value?
+14.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+19.7k Curl usage examples with Golang
+3.5k Golang : Valued expressions and functions example
+4.7k Linux/Unix/PHP : Restart PHP-FPM
+8.2k Golang : Detect number of active displays and the display's resolution
+14.9k Golang : Get IP addresses of a domain name
+26.5k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+31.2k Golang : How to check if a date is within certain range?
+2.2k Golang : Switch Redis database redis.NewClient