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?

1

2 Answers 2

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()); 
}
Sign up to request clarification or add additional context in comments.

Comments

2

And to answer the question you asked:

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

You cannot:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.