Repeat string with integer multiplication

Rust

Rust Problem Overview


Is there an easy way to do the following (from Python) in Rust?

RepeatRepeatRepeatRepeat

I'm starting to learn the language, and it seems String doesn't override Mul, and I can't find any discussion anywhere on a compact way of doing this (other than a map or loop).

Rust Solutions


Solution 1 - Rust

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.

Solution 2 - Rust

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAchal DaveView Question on Stackoverflow
Solution 1 - RustShepmasterView Answer on Stackoverflow
Solution 2 - Rustbasic_bgnrView Answer on Stackoverflow