2 ms·
There is a third variant which should also be considered: Immutable. It offers exactly the same interfaces as ReadOnly but with the additional guarantee that no
by nybble41 6y ago
There is a third variant which should also be considered: Immutable. It offers exactly the same interfaces as ReadOnly but with the additional guarantee that not only can you not mutate the object through that reference, no one else can either. Enumerating an Immutable collection or getting the item at a particular index multiple times is certain to always give you the same result, which allows simpler code and (with compiler support) better optimization.
This would be superfluous in Rust since the borrow checker ensures that no one else can mutate data that you have a reference to, but most other languages with mutation would benefit. However, the only mutable-by-default language I am aware of which directly distinguishes between read-only ("const") references and immutable data is D.