Bool -> Option<T>


#1

Sometimes I have a need to pass an Some(t) if b == true and None if b == false. Ideally, I’d like osmething like (this doesn’t compile, just for ilustratory purposes):

 impl bool {                                                                                                                                                 
     fn to_option<T>(self, v: T) -> Option<T> {                                                                                                                
         if self {                                                                                                                                           
             Some(v)                                                                                                                                         
         } else {                                                                                                                                            
             None                                                                                                                                            
         }                                                                                                                                                   
     }        
     // and maybe...  
     fn to_option_with(self, f : F) ...                                                                                                                                             
 }  

so I can do:

b.to_option(v)

It’s just shorter than

if b {  Some(v) } else { None }

Some questions:

  1. Does it make sense?
  2. What’s the best way to achive it with existing stdlib? My current approach would be a custom trait, but maybe something better can be done?
  3. Does it make enough sense to have as a crate or even ask for inclusion in stdlib?
  4. What names are best?

Your opinions are appreciated. :slight_smile:


#2

One possibility: Some(v).filter(|_| b)

Related: https://github.com/rust-lang/rust/issues/50523


#3

You could maybe even make a crate with the filter as a macro. Or you could make a trait with a single method called to_option() and impl the trait for bool.


#4

boolinator:

b.as_some(v)

#5

That works for me. :slight_smile:

Thanks everyone.