当前位置:网站首页>[rust notes] 13 iterator (Part 1)
[rust notes] 13 iterator (Part 1)
2022-07-03 08:36:00 【phial03】
13 - iterator
iterator : Is a value that can produce a series of values , Usually operate with a loop .
Example :
/// Return to the former n Sum of bit positive integers , That is to say n Number of triangles fn triangle(n: i32) -> i32 { let mut sum = 0; for i in 1..n+1 { sum += i; } sum } // Through iterators flod Method to implement the above function fn triangle(n: i32) -> i32 { (1..n+1).fold(0, |sum, item| sum + item) // fold obtain 1..n+1 Each value generated , Pass the accumulated value and this value to the closure . // Then the closure returns a new cumulative value . }
13.1-Iterator
and IntoIterator
Special type
Rust iterator : Is any implementation `std::iter::Iterator Value of special type .
trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; ... // Many default methods }
Item
Is the type of value generated by the iterator .next
Method either returnsSome(v)
, amongv
Is the next value of the iterator ; Or go back toNone
, Indicates that the sequence terminates .
IntoIterator
iterator : Implement iterations of a certain type .trait IntoIterator where Self::IntoIter::Item == Self::Item { type Item; type IntoIter: Iterator; fn into_iter(self) -> Self::IntoIter; }
Item
Is the type of value generated by the iterator .IntoIter
Is the type of iterator value itself .- Any implementation
IntoIterator
Special type , It is called an iteratable type (iterable).
Rust The loop of can realize iterative operation . Iterate over the elements of a vector as follows :
println!("There's: "); let v = vec!["antimony", "arsenic", "aluminum", "selenium"]; for element in &v { // iterator println!("{}", element); // consumer }
Each loop is essentially just a call to
IntoIterator
andIterator
Method shorthand :let mut iterator = (&v).into_iter(); while let Some(element) = iterator.next() { println!("{}", element); }
- Recycle
IntoIterator::into_iter
Method takes its operand&v
Convert to an iterator . - Then repeat the call
Iterator::next
. - Every time I go back
Some(element)
, Loops execute their loop bodies . - If you return
None
, The loop ends .
- Recycle
The value produced by the iterator is called the iteration term (item).
The code that receives the iteration items generated by the iterator is called the consumer (consumer).
13.2 - Create iterator
13.2.1-iter
and iter_mut
Method
Most collection types
iter
anditer_mut
Method , Returns an iterator of this type , Generate shared or modifiable references for each iteration item .- The iteration item type of the iterator shown below is
&i32
- Every time you call
next
Will generate a reference to the next element , Until the end of the vector .
// Instead of loops, implement iterators let v = vec![4, 20, 12, 8, 6]; let mut iterator = v.iter(); assert_eq!(iterator.next(), Some(&4)); ...
- The iteration item type of the iterator shown below is
std::path::Path
Ofiter
The iterator returned by the method will generate a component of the path each time :- The type of iteration term of this iterator is
&std::ffi::OsStr
; - It is acceptable for operating system calls 、 Borrowed string slice .
use std::ffi::OsSter; use std::path::Path; let path = Path::new("C:/users/JimB/Downloads/Fedora.iso"); let mut iterator = path.iter(); assert_eq!(iterator.next(), Some(OsStr::new("C:"))); assert_eq!(iterator.next(), Some(OsStr::new("users"))); ...
- The type of iteration term of this iterator is
13.2.2-IntoIterator
Realization
As mentioned earlier , If the type implements
IntoIterator
, You can call itsinto_iter
Method , Achieve the effect of equivalent circulation .use std::collections::BTreeSet; let mut favorites = BTreeSet::new(); favorites.insert("Lucy".to_string()); favorites.insert("Lie No. 3".to_string()); let mut it = favorites.into_iter(); assert_eq!(it.next(), Some("Lie No. 3".to_string())); assert_eq!(it.next(), Some("Lucy".to_string())); assert_eq!(it.next(), None);
Most collections implement multiple
IntoIterator
, For shared references 、 References and transfers can be modified .- Shared references to collections :
into_iter
The iterator that generates the shared reference of the iteration item is returned . - Modifiable references to collections :
into_iter
The iterator that generates the modifiable reference of the iteration item will be returned . - For the transfer by value of a set :
into_iter
The returned iterator will take ownership of the collection , And return the iterator by value . here , Ownership of iterators is transferred from binding to consumers , The original set will be consumed in this process .
- Shared references to collections :
for
A loop appliesIntoIterator::into_iter
, So the following 3 Implementation , Can support shared references to iterative collections 、 The quotation can be modified , And the combination of Consumption sets to obtain the ownership of its elements :- Each implementation , All correspond to one of the above
IntoIterator
Realization .
for element in &collection { ... } for element in &mut collection { ... } for element in collection { ... }
- Each implementation , All correspond to one of the above
HashSet
、BTreeSet
andBinaryHeap
There is no implementation of modifiable referencesIntoIterator
.HashMap
andBTreeMap
Will produce modifiable references to their values , But only generate shared references to their keys .Slicing realizes
IntoIterator
Shared references and modifiable references .IntoIterator
Implementation of shared references and modifiable references , Equivalent to calling... On a reference valueiter
oriter_mut
Method :IntoIterator
yesfor
The foundation of the bottom layer of the cycle ;- Without using
for
loop ,it.iter()
than(&it).into_iter()
Clear .
In generic code ,
T: IntoIterator
Binding can restrict type variablesT
Is an iteratable type .T: IntoIterator<Item=U>
You can further require iteration to produce the specified typeU
.// Receive any iteratable type , Pass them through {:?} Format , Print out the values use std::fmt::Debug; fn dump<T, U>(t: T) where T: IntoIterator<Item=U>, U: Debug { for u in t { println!("{:?}", u); } }
Out of commission
iter
anditer_mut
To implement this generic function , Because they are not any special method .
13.2.3-drain
Method
drain
Method : Take the modifiable reference of a set as a parameter , Returns an iterator that passes ownership of each element to the consumer .- Just borrow the reference to the collection .
- After the iterator is cleared , It will empty all the remaining elements in the collection .
Specify the type of index in the range , Such as
String
、 Vector andVecDeque
in ,drain
Method to receive the scope of the element to be removed , Instead of draining (drain) Entire sequence :use std::iter::FromIterator; let mut outer = "Eearth".to_string(); let inner = String::from_iter(outer.drain(1..4)); assert_eq!(outer, "Eh"); assert_eq!(inner, "art");
If you really want to arrange the whole sequence , Then you can use the full range (
..
) As a parameter .
13.2.4 - Other iterator sources
Type or special | expression | explain |
---|---|---|
std::ops::Range | 1..10 | The endpoint must be an integer type that can be iterated . The range contains the starting value , Does not contain a termination value . |
std::ops::RangeFrom | 1.. | Infinite iteration . The starting value must be an integer . If the value exceeds the type limit , May be surprised or overflow |
Option<T> | Some(10).iter() | Similar length is 0(None ) or 1(Some(v) ) Vector |
Result<T, E> | Ok("blah").iter() | similar Option , produce Ok value |
Vec<T>, &[T] | v.windows(16) | Each successive slice of a given length is produced from left to right . Window overlap |
v.chunks(16) | Generate non overlapping continuous slices of a given length from left to right | |
v.chunks_mut(1024) | similar chunks , But slicing is modifiable | |
`v.split( | byte | |
v.split_mut(...) | ditto , But produce modifiable slices | |
v.rsplit(...) | similar split , But slice from right to left | |
v.splitn(n, ...) | similar split , But at most n A slice | |
String, &str | s.bytes() | produce UTF-8 Bytes of form |
s.chars() | produce UTF-8 The character represented | |
s.split_whitespace() | Split the string with spaces , Generate slices of non space characters | |
s.lines() | Generate slices of string lines | |
s.split('/') | Split the string in the given pattern , Generate slices of content between matches . Patterns can be characters 、 character string 、 Closure, etc | |
s.matches(char::is_numeric) | Generate slices that match a given pattern | |
std::collections::HashMap std::collections::BTreeMap | map.keys(), map.values() | Generate shared references to mapped keys or values |
map.values_mut() | Generate modifiable references to entry values | |
std::collections::HashSet std::collections::BTreeSet | set1.union(set2) | Generate pairs set1 And set2 Shared references to collection elements |
set1.intersection(set2) | Generate pairs set1 And set2 Shared references to intersection elements | |
std::sync::mpsc::Receiver | recv.iter() | Generate the corresponding in another thread Sender Sent value |
std::io::Read | stream.bytes() | from IO Stream generates bytes |
stream.chars() | Treat flow as UTF-8 Parse and generate characters | |
std::io::BufRead | bufstream.lines() | Treat flow as UTF-8 Parse and generate String That's ok |
bufstream.split(0) | Split the stream with a given byte , Generate Vec<u8> buffer | |
std::fs::ReadDir | std::fs::read_dir(path) | Generate catalog entries |
std::net::TcpListener | listener.incoming() | Generate incoming network connections |
Free functions | std::iter::empty() | Return immediately None |
std::iter::once(5) | Produce a given value , Then the end | |
std::iter::repeat("#9") | Always produce a given value |
See 《Rust Programming 》( Jim - Brandy 、 Jason, - By orendov , Translated by lisongfeng ) Chapter 15
Original address
边栏推荐
- Student educational administration management system of C # curriculum design
- Detailed explanation of all transfer function (activation function) formulas of MATLAB neural network
- 【云原生】微服务之Feign的介绍与使用
- 796 · 开锁
- Dotween plug-in
- Data analysis exercises
- Conversion between golang JSON format and structure
- Osgearth starry background
- [concurrent programming] thread foundation and sharing between threads
- Redis的数据结构
猜你喜欢
Monotonic stack -503 Next bigger Element II
Unity editor expansion - controls, layouts
matlab神经网络所有传递函数(激活函数)公式详解
【Rust笔记】02-所有权
十六进制编码简介
Kunlunbase meetup is waiting for you!
梯度下降法求解BP神经网络的简单Demo
Detailed explanation of all transfer function (activation function) formulas of MATLAB neural network
Dotween plug-in
P1596 [USACO10OCT]Lake Counting S
随机推荐
[concurrent programming] consistency hash
Golang string segmentation, substitution and interception
UE4 source code reading_ Bone model and animation system_ Animation process
Cesium for unreal quick start - simple scenario configuration
LinkedList set
Use of ue5 QRcode plug-in
Solution détaillée de toutes les formules de fonction de transfert (fonction d'activation) du réseau neuronal MATLAB
Base64 and base64url
[MySQL] MySQL Performance Optimization Practice: introduction of database lock and index search principle
Markdown learning
matlab神经网络所有传递函数(激活函数)公式详解
[updating] wechat applet learning notes_ three
Image processing 8-cnn image classification
Get to know unity2 for the first time
Unity editor expansion - draw lines
数据分析练习题
简易入手《SOM神经网络》的本质与原理
Unity editor expansion - the design idea of imgui
【音视频】ijkplayer错误码
Animation_ IK overview