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

https://play.golang.org/p/SkDe0NFDrzX

https://play.golang.org/p/SkDe0NFDrzX

2 Likes

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 (
	"fmt"
)

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
	fmt.Println(<-c)
}

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
}

see https://play.golang.org/p/iIn3rdk92nj

2 Likes

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

2 Likes

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