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?
To print an array in Rust, we use the 😕 Operator inside the println! function.
Print Variablesprint! ("{}", age); println! ("{}", age); Here, {} is a placeholder which is replaced by the value of the variable after the comma.
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.
A contiguous growable array type, written as Vec<T> , short for 'vector'.
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
});
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>"));
let first = true;
for item in iterator {
if !first {
print(", ");
}
print(item);
first = false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With