2

When trying to print out the contents of a multidimensional vector in Rust, it seems as though you cannot use the type Vec<Vec<str>> for the vector.

fn print_multidimensional_array(multi: &Vec<Vec<str>>) {
    for y in 0..multi.len() {
        for x in 0..multi[y].len() {
            print!("{} ", multi[y][x]);
        }
        println!("");
    }
}

With this code, I get the output:

error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
 --> src/main.rs:1:1
  |
1 | / fn print_multidimensional_array(multi: &Vec<Vec<str>>) {
2 | |     for y in 0..multi.len() {
3 | |         for x in 0..multi[y].len() {
4 | |             print!("{} ", multi[y][x]);
... |
7 | |     }
8 | | }
  | |_^ `str` does not have a constant size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `str`
  = note: required by `std::vec::Vec`

What type of vector could I use for this to work?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    What process did you go through to come up with the type `Vec`? – Shepmaster Nov 17 '17 at 14:56
  • 2
    And ***please*** read [*The Rust Programming Language*](https://doc.rust-lang.org/stable/book/second-edition/) instead of trying to learn Rust by guess-and-check. – Shepmaster Nov 17 '17 at 14:58
  • 1
    @Shepmaster I'm also having a similar problem. Could you, please, point out the section reference in TRPL, as I've read it all and can't recall seeing anything helpful. This is not a complaint, but I'd like to add the observation that TRPL is definitely not the easiest document to read. In my opinion, many of its examples are considerably more complicated than they need to be, and as a learner I'm finding it quite a challenge despite having 50 years' experience of programming from Assembler to Haskell. But I hope one day to be able to help to improve it. – Brent.Longborough Mar 20 '18 at 19:05

1 Answers1

2

Use Vec<Vec<&str>>.

fn print_multidimensional_array(multi: &[Vec<&str>]) {
    for y in multi {
        for v in y {
            print!("{} ", v);
        }
        println!();
    }
}

fn main() {
    let v = vec![vec!["a", "b"], vec!["c", "d"]];
    print_multidimensional_array(&v);
}

See also:


Because I like to make things overly generic...

fn print_multidimensional_array<I>(multi: I)
where
    I: IntoIterator,
    I::Item: IntoIterator,
    <I::Item as IntoIterator>::Item: AsRef<str>,
{
    for y in multi {
        for v in y {
            print!("{} ", v.as_ref());
        }
        println!();
    }
}

fn main() {
    let v1 = vec![vec!["a", "b"], vec!["c", "d"]];
    let v2 = vec![["a", "b"], ["c", "d"]];
    let v3 = [vec!["a", "b"], vec!["c", "d"]];
    let v4 = [["a", "b"], ["c", "d"]];

    print_multidimensional_array(&v1);
    print_multidimensional_array(&v2);
    print_multidimensional_array(&v3);
    print_multidimensional_array(&v4);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366