UberStuper
UberStuper

Reputation: 466

Pass an array of strings into a function without having to specify N (compile time constant)

The following code runs:

fn last_el(arr: [&str; 2]) -> usize {
    arr.len() - 1
}

fn main() {
    let names = ["this", "that"];
    println!("{}", names[last_el(names)]);
}

However it only does so with [&str; 2] and 2 has to match the number of elements in names. For example, the following code fails to compile:

fn last_el(arr: [&str]) -> usize {
    arr.len() - 1
}

fn main(){
    let names = ["this","that"];
    println!("{}", names[last_el(names)]); 
}

How would I write this so that I don't have to specify N?

I understand that arr.len() - 1 is probably less of a headache than trying to write a function that does the same thing, but as far as understanding how functions accept arrays with strings in them, why does the second example fail to compile?

Upvotes: 3

Views: 5395

Answers (2)

Francis Gagné
Francis Gagné

Reputation: 65937

[&str] is an unsized type. You can't manipulate values of unsized types directly, they need to be behind a reference or a pointer. In your case, you should use &[&str] (also called a slice).

fn last_el(arr: &[&str]) -> usize {
    arr.len() - 1
}

fn main() {
    let names = ["this", "that"];
    println!("{}", names[last_el(&names)]);
}

I'll also note that there's a last() method defined on slices. It would be used like this:

fn main() {
    let names = ["this", "that"];
    println!("{}", names.last().unwrap()); 
}

Upvotes: 10

Shepmaster
Shepmaster

Reputation: 432109

And to answer the question you asked:

Pass an array of strings into a function without having to specify N

You cannot:

Upvotes: 2

Related Questions