Have you ever wondered why you can call iter() on Box<[T]>?
For example:
let nums = vec![1, 2, 3, 4, 5];
let box_of_slice : Box<[i32]> = nums.into_boxed_slice();
for n in box_of_slice.iter() {
println!("{}", n);
}
box_of_slice is of type Box<[i32]>, and we can iterate over it. The reason is that Box<T> implements Deref<Target = T>. Rust automatically follows the deref chain until it reaches a type that has the iter() method.
Box<[i32]> β deref β [i32] β has .iter()
But for Box<i32>, we can't call iter() because i32 isn't iterable.
Box<i32> β deref β i32 β no .iter()
i32 is a scalar with no concept of iteration. Once Box<i32> dereferences to i32, there's no iter() method to call. This is why deref coercion in Rust is so powerfulβBox<T> can act like T in terms of available methods, but only if T actually supports them.
Top comments (0)