【问题标题】:Vector of strings reports the error "str does not have a constant size known at compile time"字符串向量报告错误“str 在编译时没有已知的恒定大小”
【发布时间】:2018-05-01 09:27:35
【问题描述】:

当尝试在 Rust 中打印出多维向量的内容时,您似乎无法对向量使用类型 Vec<Vec<str>>

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!("");
    }
}

使用这段代码,我得到了输出:

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`

我可以使用什么类型的向量来实现这一点?

【问题讨论】:

  • 你是经过什么过程才想出Vec&lt;str&gt;这个类型的?
  • 并且阅读The Rust Programming Language而不是试图通过猜测和检查来学习Rust。
  • @Shepmaster 我也有类似的问题。请您指出 TRPL 中的部分参考,因为我已经阅读了所有内容并且不记得看到任何有用的内容。这不是抱怨,但我想补充一点,TRPL 绝对不是最容易阅读的文档。在我看来,它的许多示例比它们需要的复杂得多,作为一个学习者,尽管我有 50 年的从 Assembler 到 Haskell 的编程经验,但我发现它是一个相当大的挑战。但我希望有一天能够帮助改进它。

标签: vector rust


【解决方案1】:

使用Vec&lt;Vec&lt;&amp;str&gt;&gt;

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

另见:


因为我喜欢让事情过于笼统......

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

【讨论】:

  • 谢谢,这完全有效。我想我不太了解向量类型,所以这很有帮助。
猜你喜欢
  • 2018-08-29
  • 2014-09-11
  • 2014-08-18
  • 2011-03-27
  • 2012-06-23
  • 2022-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多