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
  • 388,571
  • 95
  • 1,107
  • 1,366
UberStuper
  • 356
  • 3
  • 17

2 Answers2

10

[&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()); 
}
Francis Gagné
  • 60,274
  • 7
  • 180
  • 155
2

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
  • 388,571
  • 95
  • 1,107
  • 1,366