1

I have a function that I wish to map an array to another.

Here is some simplified code that exhibits the problem. (The map does nothing; the function is useless, except to demonstrate the error.) When I un-comment the assignment, it works perfectly. However, when I try to pass in the array from outside the function it does not.

fn main(){
    let args = ["a1", "b1"];
    f( &args );
}

fn f ( args: &[&str] )  {
    //let args = ["a2", "b2"];

    println!("{args:?}");

    let args = args.map(
        |v| v
    );

    println!("{args:?}")
}

The cause of the error may be that a slice is passed. This makes sense as I will need to be able to process arrays of different lengths. And, slice does not seem to have a map function. However, I do not know how to fix it, or if my assessment is correct.

3
  • Do you want to mutate the arguments you pass in? As it is currently, it creates a new variable with the new data, then prints it without touching the old data. Commented Aug 12, 2022 at 21:51
  • Also, you can map on a slice by getting an iterator first: args.iter().map(...) Commented Aug 12, 2022 at 21:52
  • @JeremyMeadows The function is equivalent except that in the real one the map does something useful, and instead of calling println, it calls another function that also does not mutate the data. Commented Aug 12, 2022 at 22:05

1 Answer 1

1

You can use a const generic fn f<const N: usize>(args: &[&str; N]) { ... }. This way you can pass arrays with defined lengths and use the map function.

Alternatively, you can use an iterator:

let args: Vec<&str> = args.iter().map(
    |v| *v
).collect();
Sign up to request clarification or add additional context in comments.

4 Comments

I assume that the const generic will create different code for each length (or does it optimise that away). And, the size needs to be knows at compile time. Is this correct?
The const parameter makes it compile a different version for each N by mangling it into the function name. Similar to other generic parameters. And yes, the size must be known at compile time.
Do you know why we need the * (it is a de-reference, but what caused the extra level of reference?) And, what is it about collect that causes us to need the type declaration? May be that is another question.
I think I grok the * it is because of the & in the []: We pass an array of references to str.

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.