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() {
    else {

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()) }


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);

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


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.