patternrustCritical
Repeat string with integer multiplication
Viewed 0 times
withmultiplicationintegerrepeatstring
Problem
Is there an easy way to do the following (from Python) in Rust?
I'm starting to learn the language, and it seems
>>> print ("Repeat" * 4)
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).Solution
Rust 1.16+
Rust 1.0+
You can use
This also has the benefit of being more generic — it creates an infinitely repeating iterator of any type that is cloneable.
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.
Code Snippets
fn main() {
let repeated = "Repeat".repeat(4);
println!("{}", repeated);
}use std::iter;
fn main() {
let repeated: String = iter::repeat("Repeat").take(4).collect();
println!("{}", repeated);
}Context
Stack Overflow Q#31216646, score: 159
Revisions (0)
No revisions yet.