Range Over Channels

GoGoBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This lab aims to test your ability to iterate over values received from a channel using the for and range syntax in Golang.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/ConcurrencyGroup(["`Concurrency`"]) go/ConcurrencyGroup -.-> go/channels("`Channels`") subgraph Lab Skills go/channels -.-> lab-15496{{"`Range Over Channels`"}} end

Range Over Channels

You are required to write a function that takes in a channel of integers and returns the sum of all the integers received from the channel.

  • The function should be named sumInts.
  • The function should take in a single parameter of type chan int.
  • The function should return a single integer value.
  • You are not allowed to use any loops or recursion inside the function body.
  • You are not allowed to use any external packages.
$ go run range-over-channels.go
one
two

## This example also showed that it's possible to close
## a non-empty channel but still have the remaining
## values be received.

There is the full code below:

// In a [previous](range) example we saw how `for` and
// `range` provide iteration over basic data structures.
// We can also use this syntax to iterate over
// values received from a channel.

package main

import "fmt"

func main() {

	// We'll iterate over 2 values in the `queue` channel.
	queue := make(chan string, 2)
	queue <- "one"
	queue <- "two"
	close(queue)

	// This `range` iterates over each element as it's
	// received from `queue`. Because we `close`d the
	// channel above, the iteration terminates after
	// receiving the 2 elements.
	for elem := range queue {
		fmt.Println(elem)
	}
}

Summary

In this lab, you were tasked with writing a function that sums up all the integers received from a channel using the for and range syntax in Golang. By completing this lab, you should have a better understanding of how to iterate over values received from a channel and how to use goroutines to receive values from a channel.

Other Go Tutorials you may like