Idea: Properties

FWIW, my main interest in computed properties is for things that fall under the umbrella of "custom data representations". For example:

  • Bitfields

  • "Big-endian u32" and "little-endian u32" types

  • Relative pointers

  • Layout optimizations beyond what rustc does – e.g. given

    struct Foo {
        a: Option<u32>,
        b: Option<u32>,
        c: Option<u32>,
        // ...
    }
    

    it would be nice to pack all the tag bits into one word. This does mean that you can't take references to the individual Options.

Oh, and one thing that isn't a custom data representation:

  • Cell! Specifically, being able to have Cell fields without having to use .get() and .set() everywhere to access them. Atomics as well.

Each of the above examples represents an optimization of some sort:

  • Bitfields are more space-efficient than individual bool fields.
  • Fixed-endian types make it easier to work directly with data in fixed-endian format (e.g. an on-disk representation) rather than converting to a "native" representation and back.
  • Relative pointers can allow storing pointers more space-efficiently, among other things.
  • Layout optimizations are optimizations, of course.
  • Cell is usually faster than alternative designs (say, using RefCell on the entire structure); atomics can be much faster than locks.

Yet as I see it, Rust currently effectively discourages all of those optimizations, because adopting them comes with the ergonomic penalty of having to use getters and setters instead of the nice struct field syntax. And discouraging optimizations is not something Rust should be doing.

4 Likes