-3

I stumbled on something I was not expecting when using the Chars type. I called, the .next() method and found out it was mutating the original char values.

To illustrate in code and to compare with calling next on a vec:

   let mut c: Chars = "hello".chars();
   dbg!(c.next()); // prints Some("h")
   dbg!(c); // prints Chars(['e','l','l','o',])

As you can see, after calling next the h is gone, and the c value is now 'e','l','l','o'

Whereas with vec, that is not the case:

   let v1 = vec![1, 2, 3];
   let mut v1_iter = v1.iter();
   dbg!(v1_iter.next()); // prints Some(1)
   dbg!(v1); // prints [1,2,3]

As can be seen, calling next does not mutate v1 to remove the 1 element.

Why is this the case with Chars? Is it demonstrating a well defined characteristics for some type of iterators in rust that I am not aware of? That it iterators where iterating actually consumes and mutates the original value being iterated?

Finlay Weber
  • 2,989
  • 3
  • 17
  • 37
  • 2
    You're comparing apples and oranges here. In one case you're printing the iterator itself, while in the other you're printing the original container. If you print `v1_iter`, or if you do `let s = "hello"; let c = s.chars();` and print `s`, you'll notice that they behave the same. – Jmb Jul 15 '22 at 08:56

1 Answers1

2

You're comparing apples and oranges here. In one case you're printing the iterator itself, while in the other you're printing the original container. If you print v1_iter, or if you do let s = "hello"; let c = s.chars(); and print s, you'll notice that they behave the same:

let s = "hello";
let mut c: Chars = s.chars();
dbg!(c.next()); // prints Some("h")
dbg!(c); // prints Chars(['e','l','l','o',])
dbg!(s); // prints "hello"

let v1 = vec![1, 2, 3];
let mut v1_iter = v1.iter();
dbg!(v1_iter.next()); // prints Some(1)
dbg!(v1_iter); // prints Iter ([ 2, 3, ],)
dbg!(v1); // prints [1,2,3]

Playground

Jmb
  • 18,893
  • 2
  • 28
  • 55