Say I have some simple struct, eg:
struct SomeStruct {
things: Vec<usize>
recent_thing: Option<usize>
}
I'm trying to assert some invariant on this struct. For example, maybe we want to assert that "recent_thing" is only ever None just after creation (eg, with SomeStruct::new()
), and any subsequent method call will ensure it's updated.
How can you do this? In part, my solution has been the establishment of a true sentinel value (maybe Default::default()
), which, if you could restrict the user from creating its value (eg its the only value for which every byte is 0xf3), would ensure you can uphold the invariant strictly using the API (which internally upholds the invariant using typestate). You'd have to somehow make sure the user cannot use ..Default::default() in struct construction.
I dont think the solution is just Option<SomeStruct>
because that still doesn't enforce the upholding of the actual invariant.
I'm aware of this related question, whose answer is unfortunately not what I'm looking for: Can you disable constructor syntax for a type?
Also open to suggestions for improvement of the question in comments or chat
Option<usize>
, and abuild
method that converts it to the final struct that only contains ausize
, after the appropriate checks.SomeStruct
to exist withOption<usize>
between construction and first update, as far as I can tell.