Bool -> Option<T>


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 {                                                                                                                                           
         } else {                                                                                                                                            
     // and maybe...  
     fn to_option_with(self, f : F) ...                                                                                                                                             

so I can do:


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:


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



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.





That works for me. :slight_smile:

Thanks everyone.