Question mark operator in function that returns unit?
⚓ Rust 📅 2025-12-11 👤 surdeus 👁️ 4In a function body that returns Option<T>, I can use the ? operator either get the Some or early-return None.
fn foo(thing: Thing) -> Option<i32> {
let x = thing.foo()?.bar()?;
...
}
I have some code that defines an event handler function like this one below. The handler closure returns nothing (ie, ()). My typical pattern is to unwrap a few Options.
button.on_click(move |_, c| {
let Some(controller) = c.upgrade() else { return };
let Some(nav) = controller.find_navigator() else { return };
nav.pop();
}
Is there a convenient way to turn that into something like this below?
button.on_click(move |_, c| {
c.upgrade()?.find_navigator()?.pop()
}
3 posts - 2 participants
🏷️ Rust_feed