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 chapter10/recipe06.
  2. Navigate to the directory.
  3. Create the file first.go with following content:
        package main        import (          "context"          "fmt"          "sync"          "time"        )        type SearchSrc struct {          ID string          Delay int        }        func (s *SearchSrc) Search(ctx context.Context) <-chan string {          out := make(chan string)          go func() {            time.Sleep(time.Duration(s.Delay) * time.Second)            select {              case out <- "Result " + s.ID:              case <-ctx.Done():              fmt.Println("Search received Done()")            }            close(out)            fmt.Println("Search finished for ID: " + s.ID)          }()          return out        }        func main() {          ctx, cancel := context.WithCancel(context.Background())          src1 := &SearchSrc{"1", 2}          src2 := &SearchSrc{"2", 6}          r1 := src1.Search(ctx)          r2 := src2.Search(ctx)

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