I'm new to rust and I'm currently struggling with the documentation - I'm sure this is covered somewhere within the docs but I don't know where exactly
So I'm trying to use repeat with the chars function (it's an online challenge so nothing serious)
fn main() {
let s = "Test".to_string();
s.chars().repeat(2);
}
s.chars().repeat(2);
^^^^^^ method not found in `std::str::Chars<'_>`
Ok - fair enough - however where within the documentation does it inform me that repeat is incompatible with the chars iterator?
I can see within the docs that the definition of repeat is as per below but can't fathom out how this omits the chars iterator?
pub fn repeat<T>(elt: T) -> Repeat<T> where
T: Clone,
The repeat function you're looking at is for repeating a single item indefinitely. You're most likely confusing it with the str::repeat method, however to use that one you have to call it on the string directly. A character iterator does not have a repeat method.
fn main() {
let s = "Test".to_string();
for c in s.repeat(2).chars() {
println!("{}", c);
}
}
If you look at the definition of repeat, you see that it is a free-standing function, not a method (note that it doesn't take self as its first argument.) You should be using it like this:
repeat(s.chars());
You may also be confusing this with repeat_n from the itertools crate, but that is also not a method.
An "iterator" in Rust is anything that implements the Iterator trait, so the Iterator trait docs are the answer to "what works and what doesn't".
The iterator returned by chars() is.mostly the same as any other (technically there is one extra method and some extra trait impls, but almost certainly nothing that affects your code).
Also, if you're on the Chars page and look under the Trait Implementations section, you can see that it implements the Iterator trait. There you can expand the [+] boxes and see all the iterator methods that it implements, most of which come for free with every iterator.