DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Updated on

What is a Go Routine?

#go

When we develop in Go, even more when we need to do a lot of treatments in a short time, do multithreading can be really useful. And it's in this context that we will talk about Go Routines.

Definition

A Go Routine is a method which can be executed in a thread in parallel of the main thread.

How to use it

1. Declare a function which could be used by a Go Routine

func toto(from string) {
    for i := 0; i < 3; i++ {
        fmt.Println(from, ":", i)
    }
}
Enter fullscreen mode Exit fullscreen mode

As you can see, you haven't something particular to add to a function declaration to make it usable by a Go Routine.

2. Call the function as a Go Routine

To call a function as a Go Routine, you just need to add go before the function call.

// Call the function as a Go Routine
go toto("goroutine")

// Direct function call
toto("direct")
Enter fullscreen mode Exit fullscreen mode

3. Result

With the previous example, we can see that the Go Routine is called before the direct call. Let's see what the output is.

direct : 0
direct : 1
direct : 2
goroutine : 0
goroutine : 1
goroutine : 2
Enter fullscreen mode Exit fullscreen mode

We can see that "direct" call has been done before "goroutine". It shows us that the go routine was done in parallel, and a bit later than the direct call.

4. Anonymous functions

With Go Routines, we can create anonymous functions. This kind of function doesn't have a name and can't be called outside of the place where it was declared.

go func(msg string) {
        fmt.Println(msg)
    }("test")
Enter fullscreen mode Exit fullscreen mode

In this example, we can see a function which prints the message given in parameter, and the direct call of this function with "test" as parameter value.


Conclusion

To conclude this post, we can see that Go Routines are an easy way to do multithreading in Go. In a following post, we will see another Go feature which generally use Go Routines and which gives a powerful tool without external libraries, tools or plugins!

I hope it will help you! 🍺


You want to support me?

Buy Me A Coffee

Top comments (0)