The Wayback Machine - https://web.archive.org/web/20240920070414/https://www.geeksforgeeks.org/channel-in-golang/
Open In App

Channel in Golang

Last Updated : 20 Nov, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Go language, a channel is a medium through which a goroutine communicates with another goroutine and this communication is lock-free. Or in other words, a channel is a technique which allows to let one goroutine to send data to another goroutine. By default channel is bidirectional, means the goroutines can send or receive data through the same channel as shown in the below image:

Creating a Channel

In Go language, a channel is created using chan keyword and it can only transfer data of the same type, different types of data are not allowed to transport from the same channel.

Syntax:

var Channel_name chan Type

You can also create a channel using make() function using a shorthand declaration.

Syntax:

channel_name:= make(chan Type)

Example:




// Go program to illustrate
// how to create a channel
package main
  
import "fmt"
  
func main() {
  
    // Creating a channel
    // Using var keyword
    var mychannel chan int
    fmt.Println("Value of the channel: ", mychannel)
    fmt.Printf("Type of the channel: %T ", mychannel)
  
    // Creating a channel using make() function
    mychannel1 := make(chan int)
    fmt.Println("\nValue of the channel1: ", mychannel1)
    fmt.Printf("Type of the channel1: %T ", mychannel1)
}


Output:

Value of the channel:  
Type of the channel: chan int 
Value of the channel1:  0x432080
Type of the channel1: chan int 

Send and Receive Data From a Channel

In Go language, channel work with two principal operations one is sending and another one is receiving, both the operations collectively known as communication. And the direction of <- operator indicates whether the data is received or send. In the channel, the send and receive operation block until another side is not ready by default. It allows goroutine to synchronize with each other without explicit locks or condition variables.

  1. Send operation: The send operation is used to send data from one goroutine to another goroutine with the help of a channel. Values like int, float64, and bool can safe and easy to send through a channel because they are copied so there is no risk of accidental concurrent access of the same value. Similarly, strings are also safe to transfer because they are immutable. But for sending pointers or reference like a slice, map, etc. through a channel are not safe because the value of pointers or reference may change by sending goroutine or by the receiving goroutine at the same time and the result is unpredicted. So, when you use pointers or references in the channel you must make sure that they can only access by the one goroutine at a time.
    Mychannel <- element

    The above statement indicates that the data(element) send to the channel(Mychannel) with the help of a <- operator.

  2. Receive operation: The receive operation is used to receive the data sent by the send operator.
    element := <-Mychannel

    The above statement indicates that the element receives data from the channel(Mychannel). If the result of the received statement is not going to use is also a valid statement. You can also write a receive statement as:

    <-Mychannel

Example:




// Go program to illustrate send
// and receive operation
package main
  
import "fmt"
  
func myfunc(ch chan int) {
  
    fmt.Println(234 + <-ch)
}
func main() {
    fmt.Println("start Main method")
    // Creating a channel
    ch := make(chan int)
  
    go myfunc(ch)
    ch <- 23
    fmt.Println("End Main method")
}


Output:

start Main method
257
End Main method

Closing a Channel

You can also close a channel with the help of close() function. This is an in-built function and sets a flag which indicates that no more value will send to this channel.

Syntax:

close()

You can also close the channel using for range loop. Here, the receiver goroutine can check the channel is open or close with the help of the given syntax:

ele, ok:= <- Mychannel

Here, if the value of ok is true which means the channel is open so, read operations can be performed. And if the value of is false which means the channel is closed so, read operations are not going to perform.

Example:




// Go program to illustrate how
// to close a channel using for
// range loop and close function
package main
  
import "fmt"
  
// Function
func myfun(mychnl chan string) {
  
    for v := 0; v < 4; v++ {
        mychnl <- "GeeksforGeeks"
    }
    close(mychnl)
}
  
// Main function
func main() {
  
    // Creating a channel
    c := make(chan string)
  
    // calling Goroutine
    go myfun(c)
  
    // When the value of ok is
    // set to true means the
    // channel is open and it
    // can send or receive data
    // When the value of ok is set to
    // false means the channel is closed
    for {
        res, ok := <-c
        if ok == false {
            fmt.Println("Channel Close ", ok)
            break
        }
        fmt.Println("Channel Open ", res, ok)
    }
}


Output:

Channel Open  GeeksforGeeks true
Channel Open  GeeksforGeeks true
Channel Open  GeeksforGeeks true
Channel Open  GeeksforGeeks true
Channel Close  false

Important Points

  • Blocking Send and Receive: In the channel when the data sent to a channel the control is blocked in that send statement until other goroutine reads from that channel. Similarly, when a channel receives data from the goroutine the read statement block until another goroutine statement.
  • Zero Value Channel: The zero value of the channel is nil.
  • For loop in Channel: A for loop can iterate over the sequential values sent on the channel until it closed.

    Syntax:

    for item := range Chnl { 
         // statements..
    }
    

    Example:




    // Go program to illustrate how to
    // use for loop in the channel
      
    package main
      
    import "fmt"
      
    // Main function
    func main() {
      
        // Creating a channel
        // Using make() function
        mychnl := make(chan string)
      
        // Anonymous goroutine
        go func() {
            mychnl <- "GFG"
            mychnl <- "gfg"
            mychnl <- "Geeks"
            mychnl <- "GeeksforGeeks"
            close(mychnl)
        }()
      
        // Using for loop
        for res := range mychnl {
            fmt.Println(res)
        }
    }

    
    

    Output:

    GFG
    gfg
    Geeks
    GeeksforGeeks
    
    
  • Length of the Channel: In channel, you can find the length of the channel using len() function. Here, the length indicates the number of value queued in the channel buffer.

    Example:




    // Go program to illustrate how to
    // find the length of the channel
      
    package main
      
    import "fmt"
    a
    // Main function
    func main() {
      
        // Creating a channel
        // Using make() function
        mychnl := make(chan string, 4)
        mychnl <- "GFG"
        mychnl <- "gfg"
        mychnl <- "Geeks"
        mychnl <- "GeeksforGeeks"
      
        // Finding the length of the channel
        // Using len() function
        fmt.Println("Length of the channel is: ", len(mychnl))
    }

    
    

    Output:

    Length of the channel is:  4
  • Capacity of the Channel: In channel, you can find the capacity of the channel using cap() function. Here, the capacity indicates the size of the buffer.

    Example:




    // Go program to illustrate how to
    // find the capacity of the channel
      
    package main
      
    import "fmt"
      
    // Main function
    func main() {
      
        // Creating a channel
        // Using make() function
        mychnl := make(chan string, 5)
        mychnl <- "GFG"
        mychnl <- "gfg"
        mychnl <- "Geeks"
        mychnl <- "GeeksforGeeks"
      
        // Finding the capacity of the channel
        // Using cap() function
        fmt.Println("Capacity of the channel is: ", cap(mychnl))
    }

    
    

    Output:

    Capacity of the channel is:  5
  • Select and case statement in Channel: In go language, select statement is just like a switch statement without any input parameter. This select statement is used in the channel to perform a single operation out of multiple operations provided by the case block.


Previous Article
Next Article

Similar Reads

Unidirectional Channel in Golang
As we know that a channel is a medium of communication between concurrently running goroutines so that they can send and receive data to each other. By default a channel is bidirectional but you can create a unidirectional channel also. A channel that can only receive data or a channel that can only send data is the unidirectional channel. The unid
2 min read
How to find the capacity of Channel, Pointer and Slice in Golang?
Go language, capacity defines the maximum number of elements that a particular can hold. Here the task is to find the capacity of Channel, Pointer, and Slice in Golang, we can use the cap() function. Syntax: func cap(l Type) int Here, the type of l is a pointer. Let us discuss this concept with the help of the examples: Example 1: In this example,
2 min read
How to find the Length of Channel, Pointer, Slice, String and Map in Golang?
In Golang, len function is used to find the length of a channel, pointer, slice, string, and map. Channel: In Go language, a channel is a medium through which a goroutine communicates with another goroutine and this communication is lock-free. // Go program to illustrate // how to find the length a channel package main import &quot;fmt&quot; func m
2 min read
Buffered Channel in Golang
Channels can be defined as pipes used for Goroutines to communicate. Similar to how water flows from one end to another in a pipe, data can be sent from one end and received from the another end using channels. By default channels are unbuffered, which states that they will only accept sends (chan &lt;-) if there is a corresponding receive (&lt;- c
4 min read
How to convert a slice of bytes in uppercase in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to convert a slice in the uppercase usin
2 min read
Golang program that uses fallthrough keyword
With the help of fallthrough statement, we can use to transfer the program control just after the statement is executed in the switch cases even if the expression does not match. Normally, control will come out of the statement of switch just after the execution of first line after match. Don't put the fallthrough in the last statement of switch ca
2 min read
math.Lgamma() Function in Golang with Examples
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. This package provides Lgamma() function which is used to find the natural logarithm and sign (either -1 or +1) of Gamma(a). So, you need to add a math package in your program with the help of th
2 min read
math.Float64bits() Function in Golang With Examples
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. This package provides Float64bits() function which returns the IEEE 754 binary representation of a with the sign bit of a and the result in the same bit position. So, you need to add a math pack
2 min read
How to check equality of slices of bytes in Golang?
In Go language slice is more powerful, flexible, and convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence that stores elements of a similar type, you are not allowed to store different types of elements in the same slice. In the Go slice of byes, you are allowed to check the equality of the slices w
3 min read
atomic.AddInt64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddInt64() function in Go language is used to automatically add delta to the *addr. This function is defined under the atomic package. Here, you need to import "sync/atomic" package in order to use these functions. Syntax
3 min read
atomic.StoreInt64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The StoreInt64() function in Go language is used to atomically store val into *addr. This function is defined under the atomic package. Here, you need to import "sync/atomic" package in order to use these functions. Syntax: f
2 min read
reflect.FieldByIndex() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.FieldByIndex() Function in Golang is used to get the nested field corresponding to index. To access this function, one needs to imports the reflect package in the
2 min read
strings.Contains Function in Golang with Examples
strings.Contains Function in Golang is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false. Syntax: func Contains(str, substr string) bool Here, str is the original string and substr is the string that you want to check. Let us discuss th
2 min read
bits.Sub() Function in Golang with Examples
The bits.Sub() Function in Golang is used to find the difference of a, b and borrow, i.e. diff = a - b - borrow. Here the borrow must be 0 or 1; otherwise, the behavior is undefined. To access this function, one needs to imports the math/bits package in the program. The return value of the borrowOutput will be always 0 or 1 in any case. Syntax: fun
2 min read
How to convert a slice of bytes in lowercase in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to convert a slice in the lowercase usin
2 min read
io.PipeWriter.CloseWithError() Function in Golang with Examples
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The PipeWriter.CloseWithError() function in Go language is used to close the writer. However, successive reads from the PipeReader i.e, read half of the pipe will not return any
3 min read
Import in GoLang
Pre-requisite learning: Installing Go on Windows / Installing Go on MacOS Technically defining, a package is essentially a container of source code for some specific purpose. This means that the package is a capsule that holds multiple elements of drug/medicine binding them all together and protecting them in one mini shell. This capsule is easy to
9 min read
time.Round() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Round() function in Go language is used to find the outcome of rounding the stated duration 'd' to the closest multiple of 'm' duration. Here, the rounding manner for middle values is to round far off from 0. Moreover, this function is defined under th
2 min read
How to add a method to struct type in Golang?
Structs consist of data, but apart from this, structs also tell about the behavior in the form of methods. Methods attached to structs is very much similar to the definition of normal functions, the only variation is that you need to additionally specify its type. A normal function returning an integer and taking no parameter would look like. func
3 min read
Converting a string variable into Boolean, Integer or Float type in Golang
Various types of string conversions are needed while performing tasks in Golang. Package strconv is imported to perform conversions to and from string. String to Boolean Conversion ParseBool is used to convert string to boolean value. It accepts 1, t, T, TRUE, true, True as true and 0, f, F, FALSE, false, False as false. Any other value returns an
3 min read
Check if the given slice is sorted in Golang
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In Go language, you can check the given slice is sorted or not with the help of Sl
3 min read
How to compare times in Golang?
With the help of Before() and After() and Equal(), function we can compare the time as well as date but we are also going to use the time.Now() and time.Now().Add() function for comparison. Functions Used: These functions compares the times as seconds. Before(temp) - This function is used to check if the given time is before the temporary time vari
2 min read
reflect.AppendSlice() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.AppendSlice() Function in Golang is used to appends a slice t to a slice s. To access this function, one needs to imports the reflect package in the program. Synta
2 min read
How to Deploy a Golang WebApp to Heroku?
Go, also known as "Golang," is gaining popularity among DevOps professionals in recent years. There are many tools written in Go, including Docker and Kubernetes, but they can also be used for web applications and APIs. While Golang can perform as fast as a compiled language, coding in it feels more like interpreting with standard tools such as a c
5 min read
reflect.ChanOf() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.ChanOf() Function in Golang is used to get the channel type with the given direction and element type, i.e., t represents int, ChanOf(RecvDir, t) represents &lt;-c
1 min read
flag.Bool() Function in Golang With Examples
Go language provides inbuilt support for command-line parsing and has functions that could be used to define flags to be used with a command-line program using the flag package. This package provides the flag.Bool() function which is used to define a boolean flag with the specified name, default value, and usage string. Syntax: func Bool(name strin
2 min read
time.Sleep() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Sleep() function in Go language is used to stop the latest go-routine for at least the stated duration d. And a negative or zero duration of sleep will cause this method to return instantly. Moreover, this function is defined under the time package. He
3 min read
time.Time.Year() Function in Golang with Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Year() function in Go language is used to find the year in which the specified "t" happens. Moreover, this function is defined under the time package. Here, you need to import the "time" package in order to use these functions. Syntax: func (t Tim
2 min read
Searching an element of float64 type in Golang slice
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice, you can search an element of float64 type in the given slice of f
3 min read
reflect.DeepEqual() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.DeepEqual() Function in Golang is used to check whether x and y are “deeply equal” or not. To access this function, one needs to imports the reflect package in the
2 min read