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/recipe03.
  2. Navigate to the directory.
  3. Create the file once.go with the following content:
        package main        import (          "fmt"          "sync"        )        var names = []interface{}{"Alan", "Joe", "Jack", "Ben",                                  "Ellen", "Lisa", "Carl", "Steve",                                  "Anton", "Yo"}        type Source struct {          m *sync.Mutex          o *sync.Once          data []interface{}        }        func (s *Source) Pop() (interface{}, error) {          s.m.Lock()          defer s.m.Unlock()          s.o.Do(func() {            s.data = names            fmt.Println("Data has been loaded.")          })          if len(s.data) > 0 {            res := s.data[0]            s.data = s.data[1:]            return res, nil          }          return nil, fmt.Errorf("No data available")        }        func main() {          s := &Source{&sync.Mutex{}, &sync.Once{}, nil}          wg := &sync.WaitGroup{}          wg.Add(10) for i := 0; i < ...

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