如何打印Vec中每个元素的索引和值?

Nad*_*dia 1 iterator vector rust

我正在尝试完成本页底部的活动,我需要打印每个元素的索引以及值.我从代码开始

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);
}
Run Code Online (Sandbox Code Playgroud)

我是编码的新手,我通过Rust文档和Rust示例来学习Rust.我完全坚持这个.

Sta*_*eur 7

在书中你可以看到这一行:

for (count, v) in vec.iter().enumerate()
Run Code Online (Sandbox Code Playgroud)

如果您查看文档,您可以看到许多有用的函数Iteratorenumerate描述状态:

创建一个迭代器,它提供当前迭代计数以及下一个值.

迭代器返回产生对(i, val),其中i是迭代的当前索引,val是迭代器返回的值.

enumerate()保持其计数usize.如果要按不同大小的整数计数,则zip函数提供类似的功能.

这样,您就可以获得向量中每个元素的索引.做你想做的事的简单方法是使用count:

write!(f, "{}: {}", count, v)?;
Run Code Online (Sandbox Code Playgroud)