0

I have a 2D array of Strings, and I'm trying to pass it to a function as a parameter. I successfully have done this with a 2D array of i32, but with Strings I've had no luck.

An example array:

let my_string_array_2d = [
  ["Two", "Arrays", "Of"],
  ["Three", "Strings", "Each"]
];

Here is the function I'm using for a 2d Array of i32:

fn print2DIntArray<Matrix: AsRef<[Row]>, Row: AsRef<[i32]>>(x: Matrix) {
    for row in x.as_ref() {
        for cell in row.as_ref() {
            print!("{} ", cell);
        }
        println!("");
    }
}

I've tried replacing i32 with String, str and &str with no luck. I'm not a Rust developer, so it could be something simple I'm missing.

I know I can do it with a fixed dimension but I'm trying to find a generic solution.

Thanks in advance for any help.

1 Answer 1

1

You were on the right track - the inner items are string slices, so &str is the correct type. However you needed to add a lifetime annotation:

fn print_2d_int_array<'a, Matrix: AsRef<[Row]>, Row: AsRef<[&'a str]>>(x: Matrix)

Playground Link

You could make it even more generic in this case: if the objective is to be able to print the matrix, you just need to constrain the cells to be Display:

use std::fmt::Display;    

fn print_2d_int_array<Matrix: AsRef<[Row]>, Row: AsRef<[P]>, P: Display>(x: Matrix)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!!! I really appreciate this. It worked perfectly.

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.