How to print both the index and value for every element in a Vec?

拜拜、爱过 提交于 2021-02-19 06:42:11

问题


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

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.


回答1:


In the book you can see this line:

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

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.

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() keeps its count as a usize. If you want to count by a different sized integer, the zip function provides similar functionality.

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



回答2:


This is a simple example to print the index and value of a vector:

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

This program output is -

length is 5
0 1
1 2
2 3
3 4
4 5


来源:https://stackoverflow.com/questions/54795989/how-to-print-both-the-index-and-value-for-every-element-in-a-vec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!