tezvyn:

Sum Some values in Vec<Option<i32>>, ignoring None

AI-drafted, machine-checkedSource: doc.rust-lang.orgintermediate

Tests Rust Option handling and null-safety design. A strong answer uses map, unwrap_or, flatten, or match to skip Nones safely, and explains Option replaces null pointers with explicit enum variants. Red flag: using unwrap in a loop or suggesting null checks.

WHAT THIS TESTS: Your fluency with Rust's Option enum and your understanding of why it replaces nullable pointers. The interviewer wants to see safe composition using standard library tools like match, map, unwrap_or, and flatten without causing panics.

A GOOD ANSWER COVERS: First, present an idiomatic iterator solution such as values.iter().map(|x| x.unwrap_or(0)).sum(). This uses the Option method unwrap_or to replace every None with zero so they contribute nothing to the sum. Second, show the match-based manual approach: loop over the vector and match each element, adding the inner value only for Some(v) and doing nothing for None. Third, explain that Option is an enum with variants None and Some(T), so the compiler forces you to handle both cases explicitly. This design eliminates null pointer dereferences because you cannot accidentally use a missing value. Fourth, mention the Sum<Option<U>> trait implementation and warn that summing an iterator of Option<i32> directly short-circuits to None if any element is None, which is not what the question wants.

COMMON WRONG ANSWERS: Using unwrap or expect inside a loop is a red flag because it panics on None rather than ignoring it. Writing index-based for loops instead of using iterators shows a lack of Rust idioms. Returning an Option from the function is incorrect because the prompt asks for a plain sum. Suggesting that Option<i32> behaves like a nullable C pointer that needs a null check demonstrates a misunderstanding of Rust's type system.

LIKELY FOLLOW-UPS: The interviewer might ask what happens when you sum an iterator of Option<i32> directly, expecting you to cite the Sum<Option<U>> implementation and the short-circuit behavior. They may ask how to write the same logic with fold or how to avoid consuming the vector by using as_ref. They could also ask about performance differences between the iterator chain and a manual loop, which are typically identical after LLVM optimization.

ONE CONCRETE EXAMPLE: fn sum_some(values: &[Option<i32>]) -> i32 { values.iter().map(|x| x.unwrap_or(0)).sum() } This function accepts a slice for flexibility, iterates by reference, maps each Option<i32> to its inner value or zero using unwrap_or, and then sums the results. If the slice is empty or contains only None values, it correctly returns zero.

Read the original → doc.rust-lang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.