How to return a result from a goroutine

Made a function that simply sums the numbers in a slice. I’m trying to make it work with a channel. But unfortunately, not sure how to pull the results I get from my function in my main function, and output it


The main function will have to create the channel, pass it to sum as a parameter, and then read a single value from it.

package main

import (

func main() {
	c := make(chan int)
	x := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}

    // pass the data and the return channel to the goroutine
	go sum(x, c)

    // read a single value from the channel

func sum(x []int, c chan<- int) {
	total := 0
	for _, v := range x {
		total += v

    // write the result to the channel we got from main
	c <- total



Thanks a lot for your help and your recommendation on a better title. Really helped


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.