Expected Option<String>, Got Option<()> — Here's Why

rust dev.to

I'm learning Rust and recently ran into something unexpected with Option type. I expected r to be Option<&mut String>, but it came back as Option<()> instead.

Here's what I tried:

let mut vds = VecDeque::from(["a".to_owned(), "b".to_owned()]);  
let r = vds  
    .get_mut(0)  
    .and_then(|v| Some(*v = String::from("Hello")));
Enter fullscreen mode Exit fullscreen mode

It turned out to be a fundamental Rust concept: assignment is an expression, and it always evaluates to (), the empty unit type.

Here's why: *v = String::from("Hello") is an assignment, so it evaluates to (). Some() wraps that unit value, giving us Some(()). That's why r ends up as Option<()>.

Source: dev.to

arrow_back Back to Tutorials