Vector of strings reports the error “str does not

2019-08-09 23:57发布

问题:

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?

回答1:

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:

  • What does “`str` does not have a constant size known at compile-time” mean, and what's the simplest way to fix it?
  • What does "Sized is not implemented" mean?
  • Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?
  • Passing Vec<String> as IntoIterator<&'a str>
  • What are the differences between Rust's `String` and `str`?

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);
}


标签: vector rust