如何为Vec中的每个元素同时打印索引和值? [英] How to print both the index and value for every element in a Vec?

查看:38
本文介绍了如何为Vec中的每个元素同时打印索引和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在

I'm trying to complete the activity at the bottom of this page, where I need to print the index of each element as well as the value. I'm starting from the code

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文档和Rust by Example,从而学习了Rust.我完全被困住了.

I'm brand new to coding and I'm learning Rust by working my way through the Rust docs and Rust by Example. I'm totally stuck on this.

推荐答案

在书中,您可以看到以下行:

In the book you can see this line:

for (count, v) in vec.iter().enumerate()

如果您查看文档,则可以看到Iterator

If you look at the documentation, you can see a lot of useful functions for Iterator and enumerate's description states:

创建一个迭代器,该迭代器将给出当前迭代计数以及下一个值.

Creates an iterator which gives the current iteration count as well as the next value.

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

The iterator returned yields pairs (i, val), where i is the current index of iteration and val is the value returned by the iterator.

enumerate()保持其计数为usize.如果要以其他大小的整数进行计数,则zip函数提供了类似的功能.

enumerate() keeps its count as a usize. If you want to count by a different sized integer, the zip function provides similar functionality.

有了这个,您就有了向量中每个元素的索引.执行所需操作的简单方法是使用count:

With this, you have the index of each element in your vector. The simple way to do what you want is to use count:

write!(f, "{}: {}", count, v)?;

这篇关于如何为Vec中的每个元素同时打印索引和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆