News for hackers. Stuff that matters.
Re:The Smallest Thing in Go by Someone on Monday December 09, 2024 @01:27AM (#42363511)
The thing that’s remarkable is that, with iota, you can specify an expression that computes the enum value:

For example, this:

  const (
    Foo = 2 * iota // 0
    Bar = 2 * iota // 2
    Baz = 3 * iota // 6
    // ...
  )
It typically is combined with another feature, explicit repetition of the last non-empty expression list (https://go.dev/ref/spec#Constant_declarations) to avoid having to repeat the iota expression.

For a powerful example see https://go.dev/ref/spec#Iota:

By definition, multiple uses of iota in the same ConstSpec all have the same value:

  const (
    bit0, mask0 = 1 << iota, 1<<iota - 1  // bit0 == 1, mask0 == 0  (iota == 0)
    bit1, mask1                           // bit1 == 2, mask1 == 1  (iota == 1)
    _, _                                  // (iota == 2, unused)
    bit3, mask3                           // bit3 == 8, mask3 == 7  (iota == 3)
  )
I think that’s bordering on “too smart for it’s own good”, but it does prevent a very common copy-paste bug in C, where one would write something like

  enum {
    bit0 = 1 << 0,
    bit1 = 1 << 1,
    bit3 = 1 << 3,

    mask0 = bit0 - 1
    mask1 = bit1 - 1,
    mask3 = bit1 - 1 // copy-paste error
  }
(Happens fairly easily in real world code when the Enums are long, and extra Enums get added over time)
Re:The Smallest Thing in Go by Brian_K_White on Monday December 09, 2024 @12:45PM (#42368398)
Thank you. Arbitrary expression is what I was missing.