How to repeat a string multiple times in Rust? Example with multiplying a string by a number
Hello, colleagues! I just started learning Rust and encountered an unexpected problem. In Python, I'm used to writing something like `"hello" * 3` to get `"hellohellohello"`. In Rust, I tried to do the same:
```rust
fn main() {
let s = "hello" * 3;
println!("{}", s);
}
```
But the compiler gives an error: `cannot multiply `&str` by `{integer}``. I understand that Rust is a strictly typed language and multiplying strings by numbers is not defined by default, but how do you correctly repeat a string multiple times?
I've read that Rust has traits and methods, but I haven't figured it out yet. I need to repeat a string dynamically, for example, to create a separator in output: repeat `"---"` 10 times to get a string of 30 hyphens. I would also like to understand how to do this efficiently, without
No answers yet.
Log in to leave an answer
Blogs