Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> The specification now defines that struct values are compared one field at a time, considering fields in the order they appear in the struct type definition, and stopping at the first mismatch.

This is interesting because in certain cases it can be a performance hit when comparing structs which have been declared in alignment order to save memory. Simple example:

    type t struct {
      a int64
      b int32
    }

    t1 := t{a: 1, b: 2}
    t2 := t{a: 1, b: 3}
    same := t1 == t2
When comparing `t1` and `t2`, the runtime will first compare the `a` fields, which are the same, then the `b` fields, which will differ. Only after doing both comparisons will it figure out that they're different. But the `a` fields are int64, so it has to traverse these large data types before finally getting the answer.

Of course this is a trivial example, in real-world cases structs can have many more fields with much larger contents. The point is that the optimal ordering for alignment, and the optimal ordering for comparison, seem to be different.



That is just the language definition. It is fine for an implementation to actually compare both at the same time as long as within the language you can not observe this happend. If we cant tell the read to be b happenend with a or before a (hello spectre) then for the implementation it should be fine to have done the comparison.

This is more of a constraint if the struct contains a comparison that can panic. The panic must happen in order or not at all depending how the fields are listed.

  type t struct {
        a int64
        b any
  }
Should not panic on b if a values are already different.


In the few cases where it comes up, maybe you could write out the code to compare the fields in the order you choose?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: