我正在尝试完成this page底部的活动,我需要打印每个元素的索引以及值。我从代码开始
use std::fmt; // Import the `fmt` module.
// Define a structure named `List` containing a `Vec`.
struct List(Vec<i32>);
impl fmt::Display for List {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Extract the value using tuple indexing
// and create a reference to `vec`.
let vec = &self.0;
write!(f, "[")?;
// Iterate over `vec` in `v` while enumerating the iteration
// count in `count`.
for (count, v) in vec.iter().enumerate() {
// For every element except the first, add a comma.
// Use the ? operator, or try!, to return on errors.
if count != 0 { write!(f, ", ")?; }
write!(f, "{}", v)?;
}
// Close the opened bracket and return a fmt::Result value
write!(f, "]")
}
}
fn main() {
let v = List(vec![1, 2, 3]);
println!("{}", v);
}
我是编码的新手,我正在通过Rust docs和Rust by Example来学习Rust。我完全坚持这个。
在书中你可以看到这一行:
for (count, v) in vec.iter().enumerate()
如果查看文档,可以看到Iterator
和enumerate
描述的许多有用函数:
创建一个迭代器,它提供当前迭代计数以及下一个值。
返回的迭代器产生对
(i, val)
,其中i是迭代的当前索引,val是迭代器返回的值。
enumerate()
保持计数为usize
。如果要按不同大小的整数计数,则zip函数提供类似的功能。
这样,您就可以获得向量中每个元素的索引。做你想做的事的简单方法是使用count
:
write!(f, "{}: {}", count, v)?;
这是打印向量的索引和值的简单示例:
fn main() {
let vec1 = vec![1, 2, 3, 4, 5];
println!("length is {}", vec1.len());
for x in 0..vec1.len() {
println!("{} {}", x, vec1[x]);
}
}
该程序输出是 -
length is 5
0 1
1 2
2 3
3 4
4 5