[NEWBE] Calling procedure on option value

What's the most concise way to do the following?

fn main() {
    let o = Some(1);
    o.iter().for_each(|n| println!("{}", n));
}

it's o.map(|n| println!("{}", n)).

You are advised to browse the documentation of std for discovering common methods.

1 Like

Shortest that comes to mind is

fn main() {
    let o = Some(1);
    o.map(|n| println!("{}", n));
}

but you might prefer

fn main() {
    if let Some(n) = Some(1) {
        println!("{}", n);
    }
}
2 Likes

Thanks a lot for the answers.

Actually I had the if let ... solution before and thought there must be a more concise way. I've also seen map and and_then. But they both require that the function returns something, Option<U> for and_then() and U for map(), that's why I came to the iter().for_each() solution, which doesn't require any return value. But maybe that makes no difference in Rust, as U could be (), which I think is returned from C "void" like functions?

Of course it can be. Nothing in the function signature says it can't! That's the wonderful thing about Rust's type system. It's much more uniform and consistent compared to most mainstream languages. When a generic type parameter is required, there's no distinction between primitives, structs, enums, (), whatever. Every type is treated pretty much equally (as long as it upholds the capabilities described by the trait bounds in the signature).

2 Likes

Even if the solution with map is shorter, I would still say that if let is the better solution when you aren't returning a value because it's easier to read.

4 Likes

Thanks for the replies. Indeed, clippy complains about the map() solution and suggests replacing it with if let ...

1 Like

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.