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

작성자

카테고리:

← 피드로
DEV Community · Jazz Thumyat 🦀 · 2026-06-25 개발(SW)

Jazz Thumyat 🦀

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

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다