1

In C, there is the conditional operator on the form int x = foo > bar ? 1 : 0;. According to this issue, that seems to be something the Rust developers do not want to implement. If one wants to be concise: Is there a Rust equivalent/shorthand version to do the same?

struct Config {
    timeout: Option<u32>,
}

impl Config {
    
    // C-style conditional operator
    pub fn new(timeout: u32) {
        Config { 
            timeout == 0 ? None : Some(timeout) 
        }
    }

    // My attempted Rust approach
    pub fn new(timeout: u32) {
        let mut t = None;
        if timeout != 0 {
            t = Some(timeout);
        }

        Config { timeout: t }
    }
}

fn main() {
    let config = Config::new(0);
}

I guess I have two problems with the Rust approach as of now: 1) I need to create a new variable which is very hard to name anything meaningful and 2) the code is less concise than the C-style conditional operator (though perhaps more explicit).

  • 1
    Of the choices, I would go with `Config { timeout: (timeout > 0).then(|| timeout) }`. But note that you could also in this case declare it as `Option`, which is more expressive, and write `Config { timeout: NonZeroU32::new(timeout) }`. – trent Dec 12 '21 at 00:51
  • Thanks for the input. What I found based on the linked posts was `Config { timeout: if timeout != 0 { Some(timeout) } else { None } } }`, but your approach is even more concise. – magnusmaehlum Dec 12 '21 at 00:56

0 Answers0