当试图在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`
我可以使用哪种类型的矢量来实现这一目标?
答案 0 :(得分:1)
使用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);
}
另见:
因为我喜欢把事情过于通用......
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);
}