Search⌘ K
AI Features

Solution Review: Sum of Squares

Explore how to implement the Sum of Squares function using channels and select statements in Go. Learn to manage goroutines and coordinate concurrency patterns effectively. This lesson helps you understand controlling data flow and termination within concurrent Go programs.

We'll cover the following...
Go (1.6.2)
package main
import "fmt"
func SumOfSquares(c, quit chan int) {
y := 1
for {
select {
case c <- (y*y):
y++
case <-quit:
return
}
}
}
func main() {
mychannel := make(chan int)
quitchannel:= make(chan int)
sum:= 0
go func() {
for i := 1; i <= 5; i++ {
sum += <-mychannel
}
fmt.Println(sum)
quitchannel <- 0
}()
SumOfSquares(mychannel, quitchannel)
}

Let’s go over the changes we made to the SumofSquares function.

func SumOfSquares(c, quit chan int) {
  y := 1
  for {
    select {
    case c <- (y*y):
      y++
    case
...