At long last, we’re ready to learn about Go’s namesake feature!
Go statements
A “go” statement starts the execution of a function call as an independent concurrent thread of control, or goroutine, within the same address space.
GoStmt = "go" Expression .
Now before we talk about the particulars of how a go statement works, I want to set aside a common misconception, that’s subtly addressed in the above description.
Many newcomers to Go, and in fact, many seasoned Go developers, often conflate the concepts of “function” and “goroutine”, using the terms somewhat interchangeably. Some will talk about a piece of code as “a goroutine”, or with phrases such as “this function is a goroutine.”
However, these concepts are not the same!
While it may seem like a matter of trivia, or nit-picking, it can lead to some seroius confusion in certain circumstances.
Functions are collections of code. Goroutines are “independent threads of control”.
I think it can help clear up the confusion to point out that there’s not a one-to-one relationship between goroutines and functoins.
A single function can be executed by any number of goroutines, so clearly a function cannot itself be a goroutine.
Further, a typical goroutine executes many functions–it has a single function as its entry point, but then any functions that function calls (directly or indirectly), are also executed in the same goroutine. At least until another go
statement is encountered, which launches another goroutine with a new function entry point.
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)