expression

Preserve an invariant through private state

An invariant is a property that must remain true whenever an abstraction relies on it. A private bounded index is established by its constructor and cannot be changed through the public interface. The underlying array is owned by the object so no caller can shorten it. Expected stdout (not executed): 3 Common mistake: Adding a public setter that bypasses the invariant.

Formal Syntax & Structure

rust syntaxrust
private field + checked constructor

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    mod bounded {        pub struct Selected { values: [i32; 3], index: usize }        impl Selected {            pub fn new(values: [i32; 3], index: usize) -> Option<Self> {                (index < values.len()).then_some(Self { values, index })            }            pub fn value(&self) -> i32 {                // SAFETY: the private index is always < values.len();                // no public operation can change either field.                unsafe { *self.values.get_unchecked(self.index) }            }        }    }    assert!(bounded::Selected::new([1, 2, 3], 3).is_none());    println!("{}", bounded::Selected::new([1, 2, 3], 2).unwrap().value());}
Rust Reference