Iter vs into_iter on a Vec<char>

This code works, but if I first use into_iter then I can't use iter any more as letters was moved. So as I understand correctly into_iter takes ownership of the letters String while iter does not.
Does that mean that iter copies the string before creating the vector of characters?

Is this the case regardless of what we call iter vs into_iter on?

fn main() {
    let letters:Vec<char> = vec!['R', 'u', 's', 't'];

    let name = letters.iter().collect::<String>();
    println!("{name}");

    let name = letters.into_iter().collect::<String>();
    println!("{name}");
}

iter() functions borrow the data without copying the container. Although this is only a convention, it's a very strong one that you can rely on.

.collect() needs to create a new container for the data, and collecting into types like String has to copy the characters due to how String stores them in memory.

Theoretically you could collect into Vec<&char> without copying the chars, but that would be horribly counterproductive, because a reference to a char is twice as large as the char itself, and for almost every alphabet Vec of chars (UTF-32) is much larger than the same string in UTF-8.

1 Like

No, it's just that String implements FromIterator<&char>. This impl looks at and dereferences the characters one-by-one, then re-encodes them as UTF-8 bytes, appended at the end of the string.

You could thus say that the FromIterator impl "copies" the characters, but there won't ever be any chars realized in memory at once, not even while it's operating.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.