Card 1 / 12
Option<T> represents a value that might not exist: Some(value) or None β Rust's alternative to null and exceptions. Divide a by b, returning None when the quotient has no i32 result.
a |
b |
result | shows |
|---|---|---|---|
10 |
2 |
Some(5) |
happy path |
7 |
3 |
Some(2) |
integer division truncates |
5 |
0 |
None |
zero divisor |
0 |
5 |
Some(0) |
zero dividend is fine |
-2147483648 |
-1 |
None |
quotient does not fit in i32 |
There are two reasons a quotient can be absent, so None covers both: b == 0, and a == i32::MIN together with b == -1. Everything else is Some(a / b).
Why is that second pair special? i32 holds one more negative value than positive β its range is -2147483648 to 2147483647. Negating the smallest value gives 2147483648, which is one past the top of the type, so i32::MIN / -1 has no representable answer and panics if you let the division run.
/// Divide a by b, returning None when the quotient has no i32 result
fn safe_div(a: i32, b: i32) -> Option<i32> {
if b == 0 || (a == i32::MIN && b == -1) {
None
} else {
Some(a / b)
}
}Card 2 / 12
Return the index of the first occurrence of target in arr as Option<usize> β the index might not exist. enumerate() wraps an iterator so it yields (index, item) pairs.