Repeat string with integer multiplication

Rust 1.16+

str::repeat is now available:

fn main() {
    let repeated = "Repeat".repeat(4);
    println!("{}", repeated);
}

Rust 1.0+

You can use iter::repeat:

use std::iter;

fn main() {
    let repeated: String = iter::repeat("Repeat").take(4).collect();
    println!("{}", repeated);
}

This also has the benefit of being more generic — it creates an infinitely repeating iterator of any type that is cloneable.


This one doesn't use Iterator::map but Iterator::fold instead:

fn main() {
    println!("{:?}", (1..5).fold(String::new(), |b, _| b + "Repeat"));
}