How can I translate this Kotlin code using zip() and lambda functions to Rust without the explicit "for" loops?
fun main() {
val nomi = listOf("Lino", "Pino", "Bino")
val cognomi = listOf("Rossi", "Bianchi", "Verdi")
val titolo = "Dott."
val combo = nomi.zip(cognomi) { n, c -> "$titolo $n $c" }
combo.forEach { println(it) }
}
I am trying to translate this code from Kotlin to Rust. I can't figure out how to use zip() and lambda functions in a simple way like in Kotlin.
Is there a way to do this without for
loops?
fn main() {
let nomi = vec!("Lino", "Pino", "Bino");
let cognomi = vec!("Rossi", "Bianchi", "Verdi");
let titolo = "Dott.";
let mut vec = Vec::new();
for ((i,x),(j,y)) in nomi.iter().enumerate().zip(cognomi.iter().enumerate()) {
let s = ("{} {} {}", titolo, x, y);
vec.push(s)
}
for i in 0..vec.len() {
println!("{} {} {}", vec[i].1, vec[i].2, vec[i].3)
}
}
Yes, you can. They key is to use map()
and collect()
as a replacement for the first for loop, and use for_each()
for the second loop:
fn main() {
let nomi = vec!["Lino", "Pino", "Bino"];
let cognomi = vec!["Rossi", "Bianchi", "Verdi"];
let titolo = "Dott.";
let vec = nomi
.iter()
.enumerate()
.zip(cognomi.iter().enumerate())
.map(|((i, x), (j, y))| ("{} {} {}", titolo, x, y))
.collect::<Vec<_>>();
vec.iter()
.for_each(|item| println!("{} {} {}", vec[i].1, vec[i].2, vec[i].3));
}
(Note that I replaced the parentheses in vec!
with brackets; this is the recommended style and rustfmt does that automatically).
But in Rust, when we just iterate over a collection we prefer for
loops over callback-style for_each()
. If you do not want to move the Vec
, you can iterate over vec.iter()
or &vec
:
for item in &vec {
println!("{} {} {}", item.1, item.2, item.3)
}