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?