-
-
Save JonathanLoscalzo/df1de712c0582b5977105fa664116927 to your computer and use it in GitHub Desktop.
Rust: Difference between iter(), into_iter(), and iter_mut()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[test] | |
fn iter_demo() { | |
let v1 = vec![1, 2, 3]; | |
let mut v1_iter = v1.iter(); | |
// iter() returns an iterator of slices. | |
assert_eq!(v1_iter.next(), Some(&1)); | |
assert_eq!(v1_iter.next(), Some(&2)); | |
assert_eq!(v1_iter.next(), Some(&3)); | |
assert_eq!(v1_iter.next(), None); | |
} | |
#[test] | |
fn into_iter_demo() { | |
let v1 = vec![1, 2, 3]; | |
let mut v1_iter = v1.into_iter(); | |
// into_iter() returns an iterator from a value. | |
assert_eq!(v1_iter.next(), Some(1)); | |
assert_eq!(v1_iter.next(), Some(2)); | |
assert_eq!(v1_iter.next(), Some(3)); | |
assert_eq!(v1_iter.next(), None); | |
} | |
#[test] | |
fn iter_mut_demo() { | |
let mut v1 = vec![1, 2, 3]; | |
let mut v1_iter = v1.iter_mut(); | |
// iter_mut() returns an iterator that allows modifying each value. | |
assert_eq!(v1_iter.next(), Some(&mut 1)); | |
assert_eq!(v1_iter.next(), Some(&mut 2)); | |
assert_eq!(v1_iter.next(), Some(&mut 3)); | |
assert_eq!(v1_iter.next(), None); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment