3

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?

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
UberStuper
  • 356
  • 2
  • 13

2 Answers2

9

[&str] is an unsized type. You can't manipulate values of unsized types directly, they need to be behind 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()); 
}
Lukas Kalbertodt
  • 66,297
  • 20
  • 206
  • 264
Francis Gagné
  • 52,934
  • 3
  • 149
  • 138
1

And to answer the question you asked:

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

You cannot:

Community
  • 1
  • 1
Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159