DEV Community

Jazz Thumyat πŸ¦€
Jazz Thumyat πŸ¦€

Posted on

Why Does `Box<[T]>` Support `iter()` But `Box<i32>` Doesn't?

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);  
}
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

But for Box<i32>, we can't call iter() because i32 isn't iterable.

Box<i32>    β†’  deref  β†’  i32    β†’  no .iter()
Enter fullscreen mode Exit fullscreen mode

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)