Why use the `go` keyword when calling a function?
GoGo Problem Overview
I was going through an example of a TCP server. They defined a function and called it with:
go handleRequest(conn)
I thought it was weird seeing the go
keyword, so I tried it without:
handleRequest(conn)
To my surprise, this worked!
- If both work the same way, why use the
go
keyword at all? - If they work differently, what is the difference?
- Is there a certain style guideline to use, or should you just use personal preference?
Go Solutions
Solution 1 - Go
go
starts a goroutine, which is managed by golang
run-time.
It can either run on the current OS thread, or it can run on a different OS thread automatically.
You can refer to basic golang
documents for this, for example, one item in Google search keyword goroutine
is golang concurrency.
Solution 2 - Go
When you use the Go keyword before a func ure making that func run into a goRoutine, is like a Java Thread, and is the go way for concurrency, more info here. Good Luck
Solution 3 - Go
Concurrency is not well documented in the go spec and it is one of the most powerful features of the language, the go
keyword is the starting point when you are building concurrent software and not procedural software in go.
You need to look at channels as well to better understand this concept.
When you removed the go
keyword, you made the function call procedural.
Check out the talk by Rob Pike (Creator of Go) on concurrency in golang. https://www.youtube.com/watch?v=f6kdp27TYZs&t=1198s&ab_channel=GoogleDevelopers