0
fn _print_array(arr: &[i32])
{
    println!("Array : {:?}", arr);
}

pub fn print_array()
{
    let _a:[i32;3]=[1,2,3];
    _print_array(&_a);
}

fn _print_vector(v: Vec<i32>)
{
    println!("Vector : {:?}", v);
}

pub fn print_vector()
{
    let _v:Vec<i32> = vec![1, 2, 3];
    _print_vector(_v);
}

Why does an array require a reference, but a vector doesn't when we pass them as a parameter to a function?

user366312
  • 16,949
  • 65
  • 235
  • 452
  • What do you mean you can take an [array as parameter too](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=7285a96960df47df4d8a87d7dbd042df). Your first function should be called `print_slice` since that's more true to it's semantics. – cafce25 Mar 06 '23 at 20:37
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/252332/discussion-between-cafce25-and-user366312). – cafce25 Mar 06 '23 at 20:48
  • Does this answer your question? [What does "Sized is not implemented" mean?](https://stackoverflow.com/questions/28044231/what-does-sized-is-not-implemented-mean) or maybe by extension from this more relevant duplicate: [Why does Rust not allow slice as a value?](https://stackoverflow.com/questions/63793937/why-does-rust-not-allow-slice-as-a-value) – cafce25 Mar 06 '23 at 21:11

1 Answers1

1

[i32] is not an array, it's a slice. Slices are unsized, and therefore you can't pass them as function parameters. You can pass arrays.

fn print_actual_array<const LEN: usize>(arr: [i32; LEN]) {
    println!("Array : {:?}", arr);
}

You can pass unsized types using a pointer type, such as references (&), Box, or raw pointers (*const). Vec holds a *const pointer to a slice.

When you do this

let _a: [i32; 3] = [1, 2, 3];
_print_array(&_a);

you're actually coercing the array into a slice (similar to Deref or as) which looks like this explicitly

let _a: [i32; 3] = [1, 2, 3]
let _b: &[i32] = &_a;
_print_array(_b);
drewtato
  • 6,783
  • 1
  • 12
  • 17
  • The coercion in your 'explicit' variant is just as implicit as the one done by the function call, explicit coericon is written as `_a as &[i32]` – cafce25 Mar 06 '23 at 23:51