Trust iterator

Time:2022-6-21

In trust, the for loop is convenient to write because it is a syntax sugar in most cases
It’s easy to write code like Python

list_ = [1, 2, 3, 4, 5]
for item in list_:
	print(item)

This is true in trust:

let mut vector = vec![1, 2, 3, 4, 5];
for item in vector {
	println!("{}", item);
}

In the above code, the compiler does some work for us. In fact, we traverse the iterator of vector

//By default, a type that implements iterator trait is traversed directly
//Default alignment uses ` Iter() ` method, which will obtain the immutable borrowing of variables
for item: &i32 in vector.iter() {
}

You may have seen code like this:

//This is actually a call to vector iter_ Mut() ` method, using its variable borrowing
for item: &mut i32 in &mut vector {
}

//The above code is equivalent to
for item: &mut i32 in vector.iter_mut() {
}

In addition to the first time, you can alsointo_iter()To transfer ownership

let vector = vec![1, 2, 3, 4, 5];
let mut iter = v.into_iter();
// println! ("{:?}",  vector);  This will report an error because the ownership of the vector has been
//Taken by ITER

reference resources:
rust std: https://doc.rust-lang.org/std/iter/trait.IntoIterator.html#tymethod.into_iter
Trust Bible:https://course.rs/advance/functional-programing/iterator.html

Recommended Today

Vite build project steps and pits encountered, matters needing attention

Installation and startup steps install yarn First use the yarn command to install, students who do not have this command can install it firstnpm install yarn -g Install the vite project and start yarn create vite-app <project name> cd project name to enter the directory yarn install yarn dev vite configuration The configuration file is […]