I'm mostly using the Option
-way currently, but as far as I can see, both these ways have drawbacks:
With the Option
method I pay a runtime cost every time I want to access a member of that struct during the "regular" time of life of that struct. Also, there are more possible error-paths.
The mem::replace
method is in a way just the Option
method in disguise: The value that I create to replace the precious value must be created at that spot in the code, which usually means that it is some disfunctional state and kind of a None
anyway (think a unopened file). The problem here is that, if it is possible to construct such a null-like value, then the member functions of the struct typically have to deal with that possibility too and check before each access, which is like doing if let Some(x) ...
.
Ultimately, I want to make useless/disfunctional state irrepresentable, but both the Option
as well as the mem::replace
method require a useless/disfunctional state to be possible.
With this method I can avoid disfunctional state, and re-use the fields after drop.