Advertisement
AlexNovoross87

iota-enum

May 10th, 2025 (edited)
375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.95 KB | None | 0 0
  1. О iota
  2. Константа (const) похожа на переменную, но неизменяема
  3. Часто применяется группировка констант
  4. Ключевое слово iota может использоваться для
  5. автоматического присвоения значении
  6. const (              const (
  7. Online = 0           Online = iota
  8. Offline = 1          Offline
  9. Maintenance = 2      Maintenance
  10. Retired = 3          Retired
  11. )                    )
  12.  
  13. Формы:
  14. ------
  15. // Длинная:        //Короткая:
  16. const (            const (
  17. L0 = iota // 0     s0 = iota //0
  18. L1 = iota // 1     si   //  1
  19. L2 = iota // 2     s2   //  2
  20. L3 = iota // 3     s3   //  3
  21. L4 = iota // 4     s4   //  4
  22. )                  )
  23.  
  24.  
  25. Пропуск значения
  26. ----------------
  27. // Пропустить значение     // Начать с 3
  28. const (                    const (
  29. s0 = iota // 0             i3 = iota + 3 // 3 = iota + 3
  30. - // 1 (пропустить)        i4 // 4
  31. - // 2 (пропустить)        i5 // 5
  32. s3  // 3                   )
  33. s4  // 4
  34. )
  35.  
  36. iota в паттерне перечисления
  37. -----------------------------
  38. type Direction byte
  39.  
  40. const (
  41. North Direction = iota
  42. East
  43. South
  44. West
  45. )
  46.  
  47. func (d Direction) String() string {
  48.     switch d {
  49.         case North:
  50.         return fmt.Sprintf("North")
  51.         case South:
  52.         return fmt.Sprintf("South")
  53.         case East:
  54.         return fmt.Sprintf("East")
  55.         case West:
  56.         return fmt.Sprintf("West")
  57.         default: return "other direction" }
  58. }
  59.  
  60. Более короткий вариант:
  61. func (d Direction) String() string
  62. {
  63. //Создается срез, а так как Direction это byte -
  64.    достаточно вернуть значение по индексу  
  65. return []string{"North", "East", "South", "West"}[d]
  66. }
  67.  
  68. north := North
  69. fmt.Pri ntln(north) // prints "North"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement