0
votes

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

1 Answers

1
votes

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)