liveBook · Manning

Go keyword

As explained in Go in Action, Second Edition

The Go language keyword that starts a function executing as a goroutine.

A network request can block while a feed reader waits for a response. Prefix a function call with `go` to run it as a goroutine, letting the rest of the program continue. The Go runtime schedules goroutines across OS threads; no thread pool or executor needs configuring. section 9.1 section 1.4.1

Listing 9.3 main.go: Fetching data via a goroutine
package main

...

func main() {
 fp := gofeed.NewParser()
 go func(url string) { #1
  feed, _ := fp.ParseURL(url) #2
  fmt.Println(feed.Title)
 }("https://rss.nytimes.com/services/xml/rss/nyt/World.xml") #3

}

An anonymous function fetches and prints an RSS feed title. The `go` keyword starts the function call concurrently with `main`. section 9.1

Starting a goroutine does not keep the program alive. If `main` returns before the fetch finishes, the program exits and the title may never print. A fixed `time.Sleep` can make the example appear to work, but guessing a network request’s duration is not reliable synchronization. section 9.1

Listing 9.5 main.go: A second goroutine
func main() {
 go printFeedTitle("https://rss.nytimes.com/services/xml/rss/nyt/World.xml")
 go printFeedTitle("https://feeds.bbci.co.uk/news/
 rss.xml") #1
 fmt.Println("waiting....")
 time.Sleep(15 * time.Second)
 fmt.Println("stopped.")
}

Two calls to `printFeedTitle` start separate goroutines for separate news feeds. They still need a reliable way to finish before `main` returns. section 9.1

How Go in Action, Second Edition covers it

How deep it goes
Demonstrates launch syntax and the early-exit problem, but defers reliable synchronization mechanisms.
Examples
Contrasts synchronous RSS parsing with anonymous and named goroutines fetching one or two news feeds.
What it assumes
Assumes familiarity with Go function calls and `main`; introduces goroutines and their launch syntax directly.
What you can do after
Apply it via Go’s `go` keyword to launch concurrent feed fetches while accounting for completion before `main` returns.
How it connects
Connects goroutines to runtime scheduling, OS threads, network blocking, closures, and synchronization.

Also explained in

Compare how 3 books explain go keyword →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.