Golang Working with channels

Golang Working with channels

Note: To execute golang code online you can use https://play.golang.org/

Golang Channels

Channels are pipes that link between goroutines within your Go based applications that allow communication and subsequently the passing of values to and from variables.

  • Channels are goroutine-safe.
  • Channels can store and pass values between goroutines.
  • Channels provide FIFO semantics.
  • Channels cause goroutines to block and unblock, which we just learned about.

Golang Unbuffered channel

package main

import "fmt"

func calcSquare(c chan int, num int){
    c <- num * num
}

func main(){
    c := make(chan int)
    go calcSquare(c, 5)
    fmt.Println(<-c)
    // 25
    go calcSquare(c, 2)
    go calcSquare(c, 4)
    fmt.Println(<-c)
    // 4
    fmt.Println(<-c)
    // 16
}

In above program

  • we have used a channel c. we can see that to pass a value to a channel we used syntax channelName <- value to add a value to the channel
  • we have used syntax <- channelName to get the data.
  • We can also see that that program didn't stop before calculating the square of the given number as we used channel to store the data.

Golang Buffered channel

Unlike unbuffered channels buffered channels has a storage capacity.

package main

import "fmt"

func main() {
    ch := make(chan string, 2)
    ch <- "hello"
    ch <- "babe"
    fmt.Println(<-ch)
    // hello
    fmt.Println(<-ch)
    // babe
}

If we try to add a new element to the channel it will throw an error by saying fatal error: all goroutines are asleep - deadlock!.