Skip to main content

How to Pass an Array to a Function as a Slice in Rust

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

A Rust function that takes a slice, written &[T], accepts an array of any length: pass &team for the whole array or &team[1..] for part of it. The function borrows the elements, so the array stays where it was.

Syntax​

Syntax
fn <function>(<name>: &[<type>]) { ... }

<function>(&<array>);
<function>(&<array>[<start>..<end>]);
PartWhat it does
&[<type>]A slice: a view of a run of elements of that type, of any length.
& before <array>Lends the whole array to the function as a slice.
& before <array>[<start>..<end>]Lends part of it, from index <start> up to but not including <end>. Leave out <start> or <end> to go from the beginning or to the end.

The Rust Book, The Slice Type: "Slices let you reference a contiguous sequence of elements in a collection. A slice is a kind of reference, so it does not have ownership." About an array slice, it says: "This slice has the type &[i32]."

The Example​

The example has a function that prints every name in a slice of strings, and how many there were. It's called with a whole array of three names and with the same array from its second element on.

Prerequisites​

  • Rust, with Cargo. This guide uses Rust 1.100.1.

Step 1: Create the Project and Write the Code​

Terminal
cargo new demo
cd demo

cargo new demo creates a project with a src/main.rs. Replace its contents:

src/main.rs, whose print_all function takes names as a slice of str, prints each name and the count, and main calls it with the whole team array and with team from index 1.

src/main.rs
fn print_all(names: &[&str]) {
for name in names {
println!("{name}");
}
println!("{} names", names.len());
}

fn main() {
let team = ["Ada", "Grace", "Linus"];
print_all(&team);
print_all(&team[1..]);
}

Step 2: Run It​

Terminal
cargo run -q
Output
Ada
Grace
Linus
3 names
Grace
Linus
2 names

A zsh terminal where cargo run prints Ada, Grace, Linus and 3 names, then Grace, Linus and 2 names.

The command is the same in zsh, bash and PowerShell.

What Happened​

  • &team passed all three names, and names.len() was 3.
  • &team[1..] passed only the last two, from index 1 to the end, and names.len() was 2.
  • The same function handled both, because a slice's length is part of the value, not its type. An array's type includes its length: team is a [&str; 3].

That's why APIs take slices: set_issuer(&["https://login.example.org"]), for example, accepts an array of any number of issuers.

Common Mistakes​

MistakeWhat happensDo this instead
Declaring the parameter as [&str; 3]The function only accepts arrays of exactly threeTake &[&str]
Passing team instead of &teamThe types don't match: the function wants a referencePass &team
Slicing past the end, such as &team[1..5]The program panics at run timeKeep the range within team.len()

Troubleshooting​

SymptomLikely causeFix
error[E0308]: mismatched types, with expected `&[&str]`, found `[&str; 3]` An array was passed without &Add & in front of it
range end index 5 out of range for slice of length 3, in a panicThe range goes past the endUse a range that fits

FAQ​

Does passing a slice copy the elements?​

No. A slice is a reference: it points at the array's elements and stores how many there are.

Can a Vec be passed the same way?​

Yes. &my_vec also turns into a slice when the function takes &[T]: passing a Vec of two names this way printed 2.

Conclusion​

Take &[T] in a function, and pass &array or &array[range] to it. One function then works with arrays of any length and with parts of them.

Additional Resources​