Writing assignment in a single line

How can i write below code in a single line?

    let arg = Some(10);
    let ret = if arg.is_some() {
      Some(call_another_function())  
    }
    else {
        None
    };

You're probably looking for .map:

arg.map(|_| call_another_function())

If you don't like .map you could also do:

match arg { None => None, _ => Some(call_another_function()) }

(Playground)

Though this might be formatted in multiple lines same as your original example and thus not be what you are looking for. But perhaps match reads nicer than if/else. I would probably go for .map like @quinedot suggested. (Playground)

There’s also

let ret = arg.is_some().then(call_another_function);
3 Likes

Though I prefer @steffahn's solution, you shouldn't optimize writing code for "do x in a single line".

2 Likes