Why i can't pass an array as an argument to another function?

fn main() {
    println!("Hello, functions!");
    let x = [1,2,3,4,5];

fn another(array: [i32]){
    println!("Calling another func {:?}", array);

When i try to run this code its throwing an error

fn another(array: [i32]){
  |            ^^^^^ doesn't have a size known at compile-time

Why this is happing for arrays?

The type in the signature is not an array, that's a slice.

Slices are dynamically-sized, so the must always be behind indirection. You can pass a &[i32] instead.

Please, google "Rust DST" and read the relevant documentation.

1 Like

The type of x is [i32; 5], an array, not [i32], a slice. Change the type and it will work.

Arrays can be coerced to slices but slices cannot be passed directly, only indirectly via pointers: &[i32].

It is also possible to make the function generic to accept an array of arbitrary length, but that may not be what you want; more often Vec is the right choice in situations like that.


Hey @H2CO3 Thank you for your help, actually where did u find this doc link : https://doc.rust-lang.org/reference/
I actually searched in the official website of rust. I couldn't find a link there, that redirect me to this website

It is literally the first Google hit for the query "Rust DST".

This is where it is on the official website:

click “Learn”

scroll down

there it is :slight_smile:


Thank you @steffahn . This is exactly wat i was asking..

The reference is also available locally if you have installed Rust with rustup, by running rustup doc --reference (rustup doc --help also shows other potentially useful options, like rustup doc --book and rustup doc --std)


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.