golang

Golang Channels

A channel in Go refers to a technique through which goroutines can communicate. Simply put, a channel is a pipe through which you can connect concurrent goroutines, allowing for communication. Communication between goroutines is bidirectional. Thus, allowing goroutines to send and receive value through the same channel.

Golang Create Channel

Before we can use a channel in Go, we must create one. To create a channel in Go, we can use the make function to create a new channel.

The syntax is as shown:

make(chan val-type)

Keep in mind that a channel is sensitive to the data type. This means we cannot send an int value through a channel of string.

The following example creates a channel that can only support string types:

ch := make(chan string)

Once we have a channel declared, we can send and receive values.

Sending and Receiving Values

We can send and receive values using the channel <- operator. An example code is as shown below:

package main
import"fmt"
funcmain() {
    ch := make(chanstring)
    // send to channel
    gofunc() {
        ch<- "Hello"
    }()

    // recieve
    msg := <-ch
    fmt.Println(msg)

}

In the previous example, we create a basic goroutine to send the data to the channel "ch". We then receive the data from the channel and print it out.

Sending Struct via Channel

We can also send struct data through a channel, provided we create the channel with the correct type.

Consider the following code example:

package main
import"fmt"
type user struct {
    FirstName, LastNamestring
}
funcmain() {
    user1 := user{"Jane", "Doe"}
    ch := make(chan user)

    gofunc() {
        ch<- user1
    }()
    first_name := (<-ch).FirstName
    fmt.Println(first_name)

}

If we run the previous code, it should print the First Name as received by the struct sent through the channel.

Unidirectional Channels

As mentioned, Go channels are bidirectional by default. However, we can define a channel so that it can either send or receive values but not both. This is known as a unidirectional channel.

The syntax is as shown:

ch := make(chan<- data_type) // send-only channel

ch := make(<-chan data_type) // receive only channel

Notice the position of the channel operator in the previous syntax.

The following example creates a send-only channel:

package main
import"fmt"
type user struct {
    FirstName, LastNamestring
}
funcmain() {
    ch := make(chan<- string)

    gofunc ()  {
        ch<- "Hi"
    }()
    msg := <- ch
}

Note the previous channel is set to send-only. However, we try to receive through the channel, and the compiler returns an error as shown:

invalid operation: <-ch (receive from send-only type chan<- string)

Closing Channels

We can close a channel after the required values are sent. For that, we use the close function. It takes the name of the channel. It then closes the channel and returns a Boolean value which you can use to check if the channel is closed.

An example is shown below:

package main
import"fmt"

type user struct {
    FirstName, LastNamestring
}
funcmain() {
    ch := make(chanstring)
    gofunc() {
        ch<- "Hi"
    }()
    _, ok := <-ch
    close(ch)
    if !ok {
        fmt.Println("Closed...[OK]")
    }
    fmt.Println("Close...[FAIL!]")
}

The previous example closes the channel using the close() method. We then use the Boolean value returned from the function to check if the channel is closed.

Conclusion

This guide walks you through how to work with channels in the Go programming language. The process of creating a channel, sending and receiving values, sending struct data via a channel, explaining the unidirectional channels, and closing the channels were discussed. We hope you found this article helpful. Check out the other Linux Hint articles for more tips and information.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list