Advertisement
Guest User

Untitled

a guest
Jul 15th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.80 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. const defaultA = 100
  6. const defaultB = 200
  7. const defaultC = 300
  8.  
  9. type thing struct {
  10.     // Mandatory parameters
  11.     x int
  12.     y int
  13.     z int
  14.  
  15.     // Optional parameters with defaults
  16.     a int
  17.     b int
  18.     c int
  19. }
  20.  
  21. type thingOpt func(*thing)
  22.  
  23. func newThing(x, y, z int, opts ...thingOpt) *thing {
  24.     new := &thing{
  25.         x: x,
  26.         y: y,
  27.         z: z,
  28.         a: defaultA,
  29.         b: defaultB,
  30.         c: defaultC,
  31.     }
  32.  
  33.     for _, o := range opts {
  34.         o(new)
  35.     }
  36.  
  37.     return new
  38. }
  39.  
  40. func withA(a int) func(*thing) {
  41.     return func(t *thing) {
  42.         t.a = a
  43.     }
  44. }
  45.  
  46. func withB(b int) func(*thing) {
  47.     return func(t *thing) {
  48.         t.b = b
  49.     }
  50. }
  51.  
  52. func withC(c int) func(*thing) {
  53.     return func(t *thing) {
  54.         t.c = c
  55.     }
  56. }
  57.  
  58. func main() {
  59.     t := newThing(1, 2, 3, withA(10), withB(20))
  60.     fmt.Println("Thing: ", *t)
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement