libs-team
libs-team copied to clipboard
Implementing flatten for `Option<&Option<T>>` and `Option<&mut Option<T>>`
Proposal
Problem statement
Flattening a Option<&Option<T>>
is currently less intuitive then flattening a Option<Option<T>>. This also comes in true if you want to flatten a Option<&mut Option<T>>
to a mutable or immutable option.
Motivation, use-cases
This has the same use case as regular .flatten()
, just for reference types. The current alternative is to use something close to .and_then(Option::as_ref)
however it's rather unintuitive for somebody who hasn't seen it before to figure out what it does. This would be a solution that would improve the readability of code that may require it.
Solution sketches
A couple of the solution/decisions I went through:
Return Types
Option<&T>
Would require calling .as_ref()
/as_mut()
(or using a match equivalent) on the inner option. Much harder to go from Option<&T>
to &Option<T>
then vice versa.
&Option<T>
(primary solution)
Intuitive return type for the flatten, can be turned into a Option<&T>
easily with .as_ref
. However a mutable flatten cannot be constant as a &mut Option<T>
and so it would have to be kept as Option<&mut T>
.
Function naming
.flatten()
for both immutable and mutable references
Having the same function name for all flattens. Ideal for making it so people don't have to change the function name if the type changes back to being owned. However it makes it difficult to know how to turn a mutable reference into a immutable references (Option<&mut Option<T>>
-> &Option<T>
) idiomatically.
.flatten_ref()
and .flatten_mut()
(primary solution)
This allows allows for a distinction between all different return types, this way the return type is made clear since it doesn't change between the same function names. .flatten_ref()
would be returned for both mutable and immutable references and only .flatten_mut()
for mutable references.
I currently have done what It'd believe to be the ideal implementation in a pr.
Links and related work
Not much to say but thanks scottmcm in the Zulip for their thoughts on this idea!