Advertisement
cwchen

[Go] Simulating default parameters with structs

Sep 30th, 2017
865
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.83 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "log"
  5. )
  6.  
  7. type Color int
  8.  
  9. const (
  10.     White Color = iota
  11.     Black
  12.     Green
  13.     Yellow
  14. )
  15.  
  16. type Size int
  17.  
  18. const (
  19.     Large Size = iota
  20.     Middle
  21.     Small
  22.     ExtraLarge
  23. )
  24.  
  25. type Clothes struct {
  26.     color Color
  27.     size  Size
  28. }
  29.  
  30. type Param struct {
  31.     Color Color
  32.     Size  Size
  33. }
  34.  
  35. func MakeClothes(param Param) *Clothes {
  36.     c := new(Clothes)
  37.  
  38.     c.color = param.Color
  39.     c.size = param.Size
  40.  
  41.     return c
  42. }
  43.  
  44. func main() {
  45.     // Clothes with custom parameters
  46.     c1 := MakeClothes(Param{Color: Black, Size: Middle})
  47.  
  48.     if !(c1.color == Black) {
  49.         log.Fatal("Wrong color")
  50.     }
  51.  
  52.     if !(c1.size == Middle) {
  53.         log.Fatal("Wrong size")
  54.     }
  55.  
  56.     // Clothes with default parameters
  57.     c2 := MakeClothes(Param{})
  58.  
  59.     if !(c2.color == White) {
  60.         log.Fatal("Wrong color")
  61.     }
  62.  
  63.     if !(c2.size == Large) {
  64.         log.Fatal("Wrong size")
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement