Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rust, what is the best way to print something between each value in a container?

Tags:

rust

I want to print every item in a vector separated by commas. You could use numeric indexing:

for i in 0..vec.len() {
    print!("{}", vec[i]);
    if i < vec.len() - 1 {
        print!(", ");
    }
}

But what if you just have an Iterator? You either need to treat the first or last value specially, or create a custom iterator, which seems like a lot of work.

Is there a cleaner idiomatic way of expressing this in Rust?

like image 862
Michael Day Avatar asked Oct 30 '14 03:10

Michael Day


People also ask

How do you print an object in Rust?

To print an array in Rust, we use the 😕 Operator inside the println! function.

How do you print a variable in Rust?

Print Variablesprint! ("{}", age); println! ("{}", age); Here, {} is a placeholder which is replaced by the value of the variable after the comma.

What does next () do in Rust?

next() , which gives us a reference to the next value of the iterator. next returns an Option<i32> , in this case, which will be Some(i32) when we have a value and None once we run out. If we get Some(i32) , we print it out, and if we get None , we break out of the loop.

What does VEC mean in Rust?

A contiguous growable array type, written as Vec<T> , short for 'vector'.


3 Answers

If you want to avoid using a variable to check if element is first, you can make use of .take() and .skip() methods of iterators:

for e in vec.iter().take(1) {
    print!("{}", e);
}
for e in vec.iter().skip(1) {
    print!(", {}", e);
}

or compact all in a fold :

vec.iter().fold(true, |first, elem| {
    if !first { print(", "); }
    print(elem);
    false
});
like image 78
Levans Avatar answered Nov 16 '22 06:11

Levans


You can do something special for the first element, then treat all subsequent ones the same:

let mut iter = vec.iter();
if let Some(item) = iter.next() {
    print!("{}", item);

    for item in iter {
        print!("<separator>{}", item);        
    }
}

If you use Itertools::format, it's even easier:

println!("{}", vec.iter().format("<separator>"));
like image 38
Shepmaster Avatar answered Nov 16 '22 08:11

Shepmaster


let first = true;
for item in iterator {
    if !first {
        print(", ");
    }
    print(item);
    first = false;
}
like image 4
Chris Morgan Avatar answered Nov 16 '22 07:11

Chris Morgan