str::repeat¶
Level: reference · for working programmers
One line: A new String holding n copies concatenated — "ab".repeat(3) is "ababab".
Stable since 1.16.0.
Allocates once at the right size rather than growing repeatedly, so it is the right way to build a separator line or an indent.
n == 0 gives an empty string. There is no separator argument — for that, build an iterator and use join.
It can overflow. The result is len() * n bytes, and a large n will abort the process rather than silently truncate. That matters when n comes from input: a repeat count read from a file is a memory-exhaustion vector, so bound it before you use it.
For a single character, std::iter::repeat_n(c, n).collect::<String>() is equivalent; repeat is clearer when the unit is a &str.
Example¶
str_repeat.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
println!("{:?}", "ab".repeat(3));
println!("{:?}", "-".repeat(20));
println!("{:?}", "x".repeat(0));
// Indentation.
for depth in 0..4 {
println!("{}node {depth}", " ".repeat(depth));
}
// No separator argument; join supplies one.
let cells = vec!["x"; 4];
println!("{:?}", cells.join(" | "));
// Allocated once, at the final size.
let line = "=".repeat(10);
println!("{} bytes, capacity {}", line.len(), line.capacity());
// Bound a count that came from input, or the multiplication can abort.
let requested: usize = 1_000_000_000;
let safe = requested.min(32);
println!("{:?}", "!".repeat(safe));
}
Verified output of str_repeat.rs — regenerated by tools/run_examples.py, never hand-typed.
"ababab"
"--------------------"
""
node 0
node 1
node 2
node 3
"x | x | x | x"
10 bytes, capacity 10
"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
See also¶
String::with_capacity— the same one-allocation idea, done by hand- Making a
String— a single copy, viato_stringand its four rivals String::push_str— building up piece by piece insteadstr::len— the multiplication that can overflow
str::repeat in the standard library ↗
Po polsku¶
W Pythonie napisałbyś "-" * 20; w Ruście mnożenia łańcuchów znaków nie ma i tę rolę pełni repeat, które przy okazji alokuje raz, od razu na docelowy rozmiar — widać to w wydruku: 10 bajtów i pojemność 10, bez rozrastania po drodze. Separatora podać się nie da: "ab".repeat(3) to po prostu "ababab", a jeśli potrzebujesz "x | x | x | x", robotę wykonuje join na kolekcji. Jedna rzecz jest tu naprawdę groźna: wynik ma len() * n bajtów, więc licznik powtórzeń wzięty z pliku albo z żądania użytkownika staje się gotowym wektorem ataku wyczerpującego pamięć — program wtedy przerywa działanie, zamiast po cichu obciąć wynik, dlatego n trzeba ograniczyć przed użyciem, tak jak requested.min(32) w przykładzie.
Szukaj po polsku: powtarzanie łańcucha znaków · linia separatora i wcięcia · rust str repeat · rust capacity overflow allocation