Welcome to part 22 of the Go programming tutorial, where we will be discussing Go Channels. We use Go Channels to connect concurrent goroutines, in order to send and receive values between them, using the channel operator <-
. For this tutorial, we'll just use a simple example, but we'll soon be applying goroutines to our web app, which currently takes about 5 seconds to load, and we're hoping that we can speed things up significantly with what we learn here.
To begin, we'll start with a cookie-cutter script:
package main import "fmt" func main() { }
To create a channel, we use the make
built-in function, doing something like: make(chanName type)
for a simple one. Let's make:
func main() { fooVal := make(chan int) }
Next, we can start sending values over this channel by using the channel operator <-
. You use this exact same operator whether you are sending or receiving values. For example, consider you have a channel, c
, a variable called var
, and a value, v
. To send the value over a channel, you would do c <- v
. To receive a value from a channel, you would do var := <-c
.
Let's say we've got a goroutine that takes in a value and multiplies that value by 5, but we also want to retrieve these values. We've made our channel, let's write the goroutine that will work with the channel:
func foo(c chan int, someValue int) { c <- someValue * 5 }
In this case, we define the function to take in the channel and some int value. Then we send that value * 5 over the channel. Back in our main, we might do:
func main() { fooVal := make(chan int) go foo(fooVal, 5) go foo(fooVal, 3) }
So now we've got some goroutines sending some values. Let's receive them!
func main() { fooVal := make(chan int) go foo(fooVal, 5) go foo(fooVal, 3) v1 := <-fooVal v2 := <-fooVal fmt.Println(v1, v2) }
Full code up to this point:
package main import "fmt" func foo(c chan int, someValue int) { c <- someValue * 5 } func main() { fooVal := make(chan int) go foo(fooVal, 5) go foo(fooVal, 3) v1 := <-fooVal v2 := <-fooVal fmt.Println(v1, v2) }
If you run this, you should get the output of 25 15
.
Alright so that's a decent intro to channels, but, in the next tutorial, we're going to dive in a little deeper to discuss buffering, iteration, and synchronization of goroutines with channels.