example_test.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // CookieJar - A contestant's algorithm toolbox
  2. // Copyright (c) 2013 Peter Szilagyi. All rights reserved.
  3. //
  4. // CookieJar is dual licensed: use of this source code is governed by a BSD
  5. // license that can be found in the LICENSE file. Alternatively, the CookieJar
  6. // toolbox may be used in accordance with the terms and conditions contained
  7. // in a signed written agreement between you and the author(s).
  8. package bag_test
  9. import (
  10. "fmt"
  11. "gopkg.in/karalabe/cookiejar.v2/collections/bag"
  12. )
  13. // Small demo of the common functions in the bag package.
  14. func Example_usage() {
  15. // Create a new bag with some integers in it
  16. b := bag.New()
  17. for i := 0; i < 10; i++ {
  18. b.Insert(i)
  19. }
  20. b.Insert(8)
  21. // Remove every odd integer
  22. for i := 1; i < 10; i += 2 {
  23. b.Remove(i)
  24. }
  25. // Print the element count of all numbers
  26. for i := 0; i < 10; i++ {
  27. fmt.Printf("#%d: %d\n", i, b.Count(i))
  28. }
  29. // Calculate the sum with a Do iteration
  30. sum := 0
  31. b.Do(func(val interface{}) {
  32. sum += val.(int)
  33. })
  34. fmt.Println("Sum:", sum)
  35. // Output:
  36. // #0: 1
  37. // #1: 0
  38. // #2: 1
  39. // #3: 0
  40. // #4: 1
  41. // #5: 0
  42. // #6: 1
  43. // #7: 0
  44. // #8: 2
  45. // #9: 0
  46. // Sum: 28
  47. }