Code with Go
About
  • Code With Go! 🚀
  • Hello World
  • Values
  • Variables
  • Constants
  • For Loop
  • If Else
  • Switch
  • Array
  • Slice
  • Map
  • Range
  • Functions
  • Multiple Return Values
  • Variadic Functions
  • Closure
  • Recursion
  • Pointers
  • Strings and Runes
  • Structs
  • Methods
  • Interfaces
  • Struct Embedding
  • Generics
  • Error
  • Goroutines
  • Channels
  • Channel Buffering
  • Channel Synchronization
  • Channel Directions
  • Select
  • Timeouts
  • Non-Blocking Channel Operations
  • Closing Channels
  • Range over Channels
  • Timers
  • Tickers
  • Worker Pools
  • Wait Groups
  • Rate Limiting
  • Atomic Counters
  • Mutexes
  • Stateful Goroutines
  • Sorting
  • Sorting by Functions
  • Panic
  • Defer
  • Recover
  • String Functions
  • String Formatting
  • Text Templates
  • Regular Expressions
  • JSON
  • XML
  • Time
  • Epoch
  • Time Formatting / Parsing
  • Random Numbers
  • Number Parsing
  • SHA256 Hashes
  • Base64 Encoding
  • Reading Files
  • Writing Files
  • Line Filters
  • File Paths
  • Directories
  • Temporary Files and Directories
  • Embed Directive
  • Testing and Benchmarking
  • Command-Line Arguments
  • Command-Line Flags
  • Command-Line Subcommands
  • Environment Variables
  • Logging
  • HTTP Client
  • HTTP Server
  • Context
  • Spawning Processes
  • Exec'ing Processes
  • Signals
  • Exit
  • Resize Image
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub

Range over Channels

This Go code demonstrates how to use a buffered channel and the range keyword to iterate over the elements in a closed channel. Let's go through it with inline comments:

package main

import "fmt"

func main() {
    // Creating a buffered channel 'queue' with a capacity of 2
    queue := make(chan string, 2)

    // Sending two elements ("one" and "two") to the 'queue' channel
    queue <- "one"
    queue <- "two"

    // Closing the 'queue' channel to indicate that no more elements will be sent
    close(queue)

    // Iterating over the elements in the closed 'queue' channel using 'range'
    for elem := range queue {
        fmt.Println(elem)
    }
}

Output

one
two

Explanation:

  1. package main: Indicates that this Go file belongs to the main executable package.

  2. import "fmt": Imports the "fmt" package for formatting and printing.

  3. func main() { ... }: The main function, where the execution of the program begins.

  4. queue := make(chan string, 2): Creates a buffered channel named 'queue' with a capacity of 2.

  5. queue <- "one": Sends the string "one" to the 'queue' channel.

  6. queue <- "two": Sends the string "two" to the 'queue' channel.

  7. close(queue): Closes the 'queue' channel to indicate that no more elements will be sent.

  8. for elem := range queue { fmt.Println(elem) }: Uses the range keyword to iterate over the elements in the closed 'queue' channel. The loop will exit when all elements have been received. In this case, it prints "one" and "two" because these elements were sent to the channel before it was closed.

Note: Closing a channel is important when the sender wants to signal that no more values will be sent. This is especially useful when using range to iterate over a channel, as it allows the loop to exit when all values are received.

PreviousClosing ChannelsNextTimers

Last updated 1 year ago

Was this helpful?