O'Reilly logo

Go Standard Library Cookbook by Radomir Sohlich

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Open the console and create the folder chapter04/recipe11.
  2. Navigate to the directory.
  3. Create the timeout.go file with the following content:
        package main        import (          "fmt"          "time"        )        func main() {          to := time.After(3 * time.Second)          list := make([]string, 0)          done := make(chan bool, 1)          fmt.Println("Starting to insert items")          go func() {            defer fmt.Println("Exiting goroutine")            for {              select {                case <-to:                  fmt.Println("The time is up")                  done <- true                  return                default:                  list = append(list, time.Now().String())              }            }          }()          <-done          fmt.Printf("Managed to insert %d items\n", len(list))        }
  1. Execute the code by running go run timeout.go in the main Terminal.
  2. You will see the following output:

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required