← 피드로
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<()>.
추출 본문 · 출처: dev.to · https://dev.to/jazz_thumyat/expected-option-got-option-heres-why-5495
답글 남기기