code
stringlengths
2.5k
150k
kind
stringclasses
1 value
rust Module std::collections::hash_set Module std::collections::hash\_set ================================== A hash set implemented as a `HashMap` where the value is `()`. Structs ------- [DrainFilter](struct.drainfilter "std::collections::hash_set::DrainFilter struct")Experimental A draining, filtering iterator over the items of a `HashSet`. [Difference](struct.difference "std::collections::hash_set::Difference struct") A lazy iterator producing elements in the difference of `HashSet`s. [Drain](struct.drain "std::collections::hash_set::Drain struct") A draining iterator over the items of a `HashSet`. [HashSet](struct.hashset "std::collections::hash_set::HashSet struct") A [hash set](../index#use-the-set-variant-of-any-of-these-maps-when) implemented as a `HashMap` where the value is `()`. [Intersection](struct.intersection "std::collections::hash_set::Intersection struct") A lazy iterator producing elements in the intersection of `HashSet`s. [IntoIter](struct.intoiter "std::collections::hash_set::IntoIter struct") An owning iterator over the items of a `HashSet`. [Iter](struct.iter "std::collections::hash_set::Iter struct") An iterator over the items of a `HashSet`. [SymmetricDifference](struct.symmetricdifference "std::collections::hash_set::SymmetricDifference struct") A lazy iterator producing elements in the symmetric difference of `HashSet`s. [Union](struct.union "std::collections::hash_set::Union struct") A lazy iterator producing elements in the union of `HashSet`s. rust Struct std::collections::hash_set::HashSet Struct std::collections::hash\_set::HashSet =========================================== ``` pub struct HashSet<T, S = RandomState> { /* private fields */ } ``` A [hash set](../index#use-the-set-variant-of-any-of-these-maps-when) implemented as a `HashMap` where the value is `()`. As with the [`HashMap`](../hash_map/struct.hashmap) type, a `HashSet` requires that the elements implement the [`Eq`](../../cmp/trait.eq "Eq") and [`Hash`](../../hash/trait.hash "Hash") traits. This can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself, it is important that the following property holds: ``` k1 == k2 -> hash(k1) == hash(k2) ``` In other words, if two keys are equal, their hashes must be equal. It is a logic error for a key to be modified in such a way that the key’s hash, as determined by the [`Hash`](../../hash/trait.hash "Hash") trait, or its equality, as determined by the [`Eq`](../../cmp/trait.eq "Eq") trait, changes while it is in the map. This is normally only possible through [`Cell`](../../cell/struct.cell), [`RefCell`](../../cell/struct.refcell), global state, I/O, or unsafe code. The behavior resulting from such a logic error is not specified, but will be encapsulated to the `HashSet` that observed the logic error and not result in undefined behavior. This could include panics, incorrect results, aborts, memory leaks, and non-termination. Examples -------- ``` use std::collections::HashSet; // Type inference lets us omit an explicit type signature (which // would be `HashSet<String>` in this example). let mut books = HashSet::new(); // Add some books. books.insert("A Dance With Dragons".to_string()); books.insert("To Kill a Mockingbird".to_string()); books.insert("The Odyssey".to_string()); books.insert("The Great Gatsby".to_string()); // Check for a specific one. if !books.contains("The Winds of Winter") { println!("We have {} books, but The Winds of Winter ain't one.", books.len()); } // Remove a book. books.remove("The Odyssey"); // Iterate over everything. for book in &books { println!("{book}"); } ``` The easiest way to use `HashSet` with a custom type is to derive [`Eq`](../../cmp/trait.eq "Eq") and [`Hash`](../../hash/trait.hash "Hash"). We must also derive [`PartialEq`](../../cmp/trait.partialeq "PartialEq"), this will in the future be implied by [`Eq`](../../cmp/trait.eq "Eq"). ``` use std::collections::HashSet; #[derive(Hash, Eq, PartialEq, Debug)] struct Viking { name: String, power: usize, } let mut vikings = HashSet::new(); vikings.insert(Viking { name: "Einar".to_string(), power: 9 }); vikings.insert(Viking { name: "Einar".to_string(), power: 9 }); vikings.insert(Viking { name: "Olaf".to_string(), power: 4 }); vikings.insert(Viking { name: "Harald".to_string(), power: 8 }); // Use derived implementation to print the vikings. for x in &vikings { println!("{x:?}"); } ``` A `HashSet` with a known list of items can be initialized from an array: ``` use std::collections::HashSet; let viking_names = HashSet::from(["Einar", "Olaf", "Harald"]); ``` Implementations --------------- [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#117-155)### impl<T> HashSet<T, RandomState> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#132-134)#### pub fn new() -> HashSet<T, RandomState> Creates an empty `HashSet`. The hash set is initially created with a capacity of 0, so it will not allocate until it is first inserted into. ##### Examples ``` use std::collections::HashSet; let set: HashSet<i32> = HashSet::new(); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#152-154)#### pub fn with\_capacity(capacity: usize) -> HashSet<T, RandomState> Creates an empty `HashSet` with at least the specified capacity. The hash set will be able to hold at least `capacity` elements without reallocating. This method is allowed to allocate for more elements than `capacity`. If `capacity` is 0, the hash set will not allocate. ##### Examples ``` use std::collections::HashSet; let set: HashSet<i32> = HashSet::with_capacity(10); assert!(set.capacity() >= 10); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#157-431)### impl<T, S> HashSet<T, S> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#169-171)#### pub fn capacity(&self) -> usize Returns the number of elements the set can hold without reallocating. ##### Examples ``` use std::collections::HashSet; let set: HashSet<i32> = HashSet::with_capacity(100); assert!(set.capacity() >= 100); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#197-199)#### pub fn iter(&self) -> Iter<'\_, T> Notable traits for [Iter](struct.iter "struct std::collections::hash_set::Iter")<'a, K> ``` impl<'a, K> Iterator for Iter<'a, K> type Item = &'a K; ``` An iterator visiting all elements in arbitrary order. The iterator element type is `&'a T`. ##### Examples ``` use std::collections::HashSet; let mut set = HashSet::new(); set.insert("a"); set.insert("b"); // Will print in an arbitrary order. for x in set.iter() { println!("{x}"); } ``` ##### Performance In the current implementation, iterating over set takes O(capacity) time instead of O(len) because it internally visits empty buckets too. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#215-217)#### pub fn len(&self) -> usize Returns the number of elements in the set. ##### Examples ``` use std::collections::HashSet; let mut v = HashSet::new(); assert_eq!(v.len(), 0); v.insert(1); assert_eq!(v.len(), 1); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#233-235)#### pub fn is\_empty(&self) -> bool Returns `true` if the set contains no elements. ##### Examples ``` use std::collections::HashSet; let mut v = HashSet::new(); assert!(v.is_empty()); v.insert(1); assert!(!v.is_empty()); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#262-264)1.6.0 · #### pub fn drain(&mut self) -> Drain<'\_, T> Notable traits for [Drain](struct.drain "struct std::collections::hash_set::Drain")<'a, K> ``` impl<'a, K> Iterator for Drain<'a, K> type Item = K; ``` Clears the set, returning all elements as an iterator. Keeps the allocated memory for reuse. If the returned iterator is dropped before being fully consumed, it drops the remaining elements. The returned iterator keeps a mutable borrow on the set to optimize its implementation. ##### Examples ``` use std::collections::HashSet; let mut set = HashSet::from([1, 2, 3]); assert!(!set.is_empty()); // print 1, 2, 3 in an arbitrary order for i in set.drain() { println!("{i}"); } assert!(set.is_empty()); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#301-306)#### pub fn drain\_filter<F>(&mut self, pred: F) -> DrainFilter<'\_, T, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), Notable traits for [DrainFilter](struct.drainfilter "struct std::collections::hash_set::DrainFilter")<'\_, K, F> ``` impl<K, F> Iterator for DrainFilter<'_, K, F>where     F: FnMut(&K) -> bool, type Item = K; ``` 🔬This is a nightly-only experimental API. (`hash_drain_filter` [#59618](https://github.com/rust-lang/rust/issues/59618)) Creates an iterator which uses a closure to determine if a value should be removed. If the closure returns true, then the value is removed and yielded. If the closure returns false, the value will remain in the list and will not be yielded by the iterator. If the iterator is only partially consumed or not consumed at all, each of the remaining values will still be subjected to the closure and removed and dropped if it returns true. It is unspecified how many more values will be subjected to the closure if a panic occurs in the closure, or if a panic occurs while dropping a value, or if the `DrainFilter` itself is leaked. ##### Examples Splitting a set into even and odd values, reusing the original set: ``` #![feature(hash_drain_filter)] use std::collections::HashSet; let mut set: HashSet<i32> = (0..8).collect(); let drained: HashSet<i32> = set.drain_filter(|v| v % 2 == 0).collect(); let mut evens = drained.into_iter().collect::<Vec<_>>(); let mut odds = set.into_iter().collect::<Vec<_>>(); evens.sort(); odds.sort(); assert_eq!(evens, vec![0, 2, 4, 6]); assert_eq!(odds, vec![1, 3, 5, 7]); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#329-334)1.18.0 · #### pub fn retain<F>(&mut self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), Retains only the elements specified by the predicate. In other words, remove all elements `e` for which `f(&e)` returns `false`. The elements are visited in unsorted (and unspecified) order. ##### Examples ``` use std::collections::HashSet; let mut set = HashSet::from([1, 2, 3, 4, 5, 6]); set.retain(|&k| k % 2 == 0); assert_eq!(set.len(), 3); ``` ##### Performance In the current implementation, this operation takes O(capacity) time instead of O(len) because it internally visits empty buckets too. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#350-352)#### pub fn clear(&mut self) Clears the set, removing all values. ##### Examples ``` use std::collections::HashSet; let mut v = HashSet::new(); v.insert(1); v.clear(); assert!(v.is_empty()); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#379-381)1.7.0 · #### pub fn with\_hasher(hasher: S) -> HashSet<T, S> Creates a new empty hash set which will use the given hasher to hash keys. The hash set is also created with the default initial capacity. Warning: `hasher` is normally randomly generated, and is designed to allow `HashSet`s to be resistant to attacks that cause many collisions and very poor performance. Setting it manually using this function can expose a DoS attack vector. The `hash_builder` passed should implement the [`BuildHasher`](../../hash/trait.buildhasher "BuildHasher") trait for the HashMap to be useful, see its documentation for details. ##### Examples ``` use std::collections::HashSet; use std::collections::hash_map::RandomState; let s = RandomState::new(); let mut set = HashSet::with_hasher(s); set.insert(2); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#410-412)1.7.0 · #### pub fn with\_capacity\_and\_hasher(capacity: usize, hasher: S) -> HashSet<T, S> Creates an empty `HashSet` with at least the specified capacity, using `hasher` to hash the keys. The hash set will be able to hold at least `capacity` elements without reallocating. This method is allowed to allocate for more elements than `capacity`. If `capacity` is 0, the hash set will not allocate. Warning: `hasher` is normally randomly generated, and is designed to allow `HashSet`s to be resistant to attacks that cause many collisions and very poor performance. Setting it manually using this function can expose a DoS attack vector. The `hash_builder` passed should implement the [`BuildHasher`](../../hash/trait.buildhasher "BuildHasher") trait for the HashMap to be useful, see its documentation for details. ##### Examples ``` use std::collections::HashSet; use std::collections::hash_map::RandomState; let s = RandomState::new(); let mut set = HashSet::with_capacity_and_hasher(10, s); set.insert(1); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#428-430)1.9.0 · #### pub fn hasher(&self) -> &S Returns a reference to the set’s [`BuildHasher`](../../hash/trait.buildhasher "BuildHasher"). ##### Examples ``` use std::collections::HashSet; use std::collections::hash_map::RandomState; let hasher = RandomState::new(); let set: HashSet<i32> = HashSet::with_hasher(hasher); let hasher: &RandomState = set.hasher(); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#433-969)### impl<T, S> HashSet<T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#458-460)#### pub fn reserve(&mut self, additional: usize) Reserves capacity for at least `additional` more elements to be inserted in the `HashSet`. The collection may reserve more space to speculatively avoid frequent reallocations. After calling `reserve`, capacity will be greater than or equal to `self.len() + additional`. Does nothing if capacity is already sufficient. ##### Panics Panics if the new allocation size overflows `usize`. ##### Examples ``` use std::collections::HashSet; let mut set: HashSet<i32> = HashSet::new(); set.reserve(10); assert!(set.capacity() >= 10); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#483-485)1.57.0 · #### pub fn try\_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> Tries to reserve capacity for at least `additional` more elements to be inserted in the `HashSet`. The collection may reserve more space to speculatively avoid frequent reallocations. After calling `reserve`, capacity will be greater than or equal to `self.len() + additional` if it returns `Ok(())`. Does nothing if capacity is already sufficient. ##### Errors If the capacity overflows, or the allocator reports a failure, then an error is returned. ##### Examples ``` use std::collections::HashSet; let mut set: HashSet<i32> = HashSet::new(); set.try_reserve(10).expect("why is the test harness OOMing on a handful of bytes?"); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#505-507)#### pub fn shrink\_to\_fit(&mut self) Shrinks the capacity of the set as much as possible. It will drop down as much as possible while maintaining the internal rules and possibly leaving some space in accordance with the resize policy. ##### Examples ``` use std::collections::HashSet; let mut set = HashSet::with_capacity(100); set.insert(1); set.insert(2); assert!(set.capacity() >= 100); set.shrink_to_fit(); assert!(set.capacity() >= 2); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#530-532)1.56.0 · #### pub fn shrink\_to(&mut self, min\_capacity: usize) Shrinks the capacity of the set with a lower limit. It will drop down no lower than the supplied limit while maintaining the internal rules and possibly leaving some space in accordance with the resize policy. If the current capacity is less than the lower limit, this is a no-op. ##### Examples ``` use std::collections::HashSet; let mut set = HashSet::with_capacity(100); set.insert(1); set.insert(2); assert!(set.capacity() >= 100); set.shrink_to(10); assert!(set.capacity() >= 10); set.shrink_to(0); assert!(set.capacity() >= 2); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#560-562)#### pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> Notable traits for [Difference](struct.difference "struct std::collections::hash_set::Difference")<'a, T, S> ``` impl<'a, T, S> Iterator for Difference<'a, T, S>where     T: Eq + Hash,     S: BuildHasher, type Item = &'a T; ``` Visits the values representing the difference, i.e., the values that are in `self` but not in `other`. ##### Examples ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let b = HashSet::from([4, 2, 3, 4]); // Can be seen as `a - b`. for x in a.difference(&b) { println!("{x}"); // Print 1 } let diff: HashSet<_> = a.difference(&b).collect(); assert_eq!(diff, [1].iter().collect()); // Note that difference is not symmetric, // and `b - a` means something else: let diff: HashSet<_> = b.difference(&a).collect(); assert_eq!(diff, [4].iter().collect()); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#588-593)#### pub fn symmetric\_difference<'a>( &'a self, other: &'a HashSet<T, S>) -> SymmetricDifference<'a, T, S> Notable traits for [SymmetricDifference](struct.symmetricdifference "struct std::collections::hash_set::SymmetricDifference")<'a, T, S> ``` impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>where     T: Eq + Hash,     S: BuildHasher, type Item = &'a T; ``` Visits the values representing the symmetric difference, i.e., the values that are in `self` or in `other` but not in both. ##### Examples ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let b = HashSet::from([4, 2, 3, 4]); // Print 1, 4 in arbitrary order. for x in a.symmetric_difference(&b) { println!("{x}"); } let diff1: HashSet<_> = a.symmetric_difference(&b).collect(); let diff2: HashSet<_> = b.symmetric_difference(&a).collect(); assert_eq!(diff1, diff2); assert_eq!(diff1, [1, 4].iter().collect()); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#622-628)#### pub fn intersection<'a>( &'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> Notable traits for [Intersection](struct.intersection "struct std::collections::hash_set::Intersection")<'a, T, S> ``` impl<'a, T, S> Iterator for Intersection<'a, T, S>where     T: Eq + Hash,     S: BuildHasher, type Item = &'a T; ``` Visits the values representing the intersection, i.e., the values that are both in `self` and `other`. When an equal element is present in `self` and `other` then the resulting `Intersection` may yield references to one or the other. This can be relevant if `T` contains fields which are not compared by its `Eq` implementation, and may hold different value between the two equal copies of `T` in the two sets. ##### Examples ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let b = HashSet::from([4, 2, 3, 4]); // Print 2, 3 in arbitrary order. for x in a.intersection(&b) { println!("{x}"); } let intersection: HashSet<_> = a.intersection(&b).collect(); assert_eq!(intersection, [2, 3].iter().collect()); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#651-657)#### pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> Notable traits for [Union](struct.union "struct std::collections::hash_set::Union")<'a, T, S> ``` impl<'a, T, S> Iterator for Union<'a, T, S>where     T: Eq + Hash,     S: BuildHasher, type Item = &'a T; ``` Visits the values representing the union, i.e., all the values in `self` or `other`, without duplicates. ##### Examples ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let b = HashSet::from([4, 2, 3, 4]); // Print 1, 2, 3, 4 in arbitrary order. for x in a.union(&b) { println!("{x}"); } let union: HashSet<_> = a.union(&b).collect(); assert_eq!(union, [1, 2, 3, 4].iter().collect()); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#676-682)#### pub fn contains<Q: ?Sized>(&self, value: &Q) -> boolwhere T: [Borrow](../../borrow/trait.borrow "trait std::borrow::Borrow")<Q>, Q: [Hash](../../hash/trait.hash "trait std::hash::Hash") + [Eq](../../cmp/trait.eq "trait std::cmp::Eq"), Returns `true` if the set contains a value. The value may be any borrowed form of the set’s value type, but [`Hash`](../../hash/trait.hash "Hash") and [`Eq`](../../cmp/trait.eq "Eq") on the borrowed form *must* match those for the value type. ##### Examples ``` use std::collections::HashSet; let set = HashSet::from([1, 2, 3]); assert_eq!(set.contains(&1), true); assert_eq!(set.contains(&4), false); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#701-707)1.9.0 · #### pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>where T: [Borrow](../../borrow/trait.borrow "trait std::borrow::Borrow")<Q>, Q: [Hash](../../hash/trait.hash "trait std::hash::Hash") + [Eq](../../cmp/trait.eq "trait std::cmp::Eq"), Returns a reference to the value in the set, if any, that is equal to the given value. The value may be any borrowed form of the set’s value type, but [`Hash`](../../hash/trait.hash "Hash") and [`Eq`](../../cmp/trait.eq "Eq") on the borrowed form *must* match those for the value type. ##### Examples ``` use std::collections::HashSet; let set = HashSet::from([1, 2, 3]); assert_eq!(set.get(&2), Some(&2)); assert_eq!(set.get(&4), None); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#727-731)#### pub fn get\_or\_insert(&mut self, value: T) -> &T 🔬This is a nightly-only experimental API. (`hash_set_entry` [#60896](https://github.com/rust-lang/rust/issues/60896)) Inserts the given `value` into the set if it is not present, then returns a reference to the value in the set. ##### Examples ``` #![feature(hash_set_entry)] use std::collections::HashSet; let mut set = HashSet::from([1, 2, 3]); assert_eq!(set.len(), 3); assert_eq!(set.get_or_insert(2), &2); assert_eq!(set.get_or_insert(100), &100); assert_eq!(set.len(), 4); // 100 was inserted ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#755-763)#### pub fn get\_or\_insert\_owned<Q: ?Sized>(&mut self, value: &Q) -> &Twhere T: [Borrow](../../borrow/trait.borrow "trait std::borrow::Borrow")<Q>, Q: [Hash](../../hash/trait.hash "trait std::hash::Hash") + [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [ToOwned](../../borrow/trait.toowned "trait std::borrow::ToOwned")<Owned = T>, 🔬This is a nightly-only experimental API. (`hash_set_entry` [#60896](https://github.com/rust-lang/rust/issues/60896)) Inserts an owned copy of the given `value` into the set if it is not present, then returns a reference to the value in the set. ##### Examples ``` #![feature(hash_set_entry)] use std::collections::HashSet; let mut set: HashSet<String> = ["cat", "dog", "horse"] .iter().map(|&pet| pet.to_owned()).collect(); assert_eq!(set.len(), 3); for &pet in &["cat", "dog", "fish"] { let value = set.get_or_insert_owned(pet); assert_eq!(value, pet); } assert_eq!(set.len(), 4); // a new "fish" was inserted ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#787-796)#### pub fn get\_or\_insert\_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &Twhere T: [Borrow](../../borrow/trait.borrow "trait std::borrow::Borrow")<Q>, Q: [Hash](../../hash/trait.hash "trait std::hash::Hash") + [Eq](../../cmp/trait.eq "trait std::cmp::Eq"), F: [FnOnce](../../ops/trait.fnonce "trait std::ops::FnOnce")([&](../../primitive.reference)Q) -> T, 🔬This is a nightly-only experimental API. (`hash_set_entry` [#60896](https://github.com/rust-lang/rust/issues/60896)) Inserts a value computed from `f` into the set if the given `value` is not present, then returns a reference to the value in the set. ##### Examples ``` #![feature(hash_set_entry)] use std::collections::HashSet; let mut set: HashSet<String> = ["cat", "dog", "horse"] .iter().map(|&pet| pet.to_owned()).collect(); assert_eq!(set.len(), 3); for &pet in &["cat", "dog", "fish"] { let value = set.get_or_insert_with(pet, str::to_owned); assert_eq!(value, pet); } assert_eq!(set.len(), 4); // a new "fish" was inserted ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#816-822)#### pub fn is\_disjoint(&self, other: &HashSet<T, S>) -> bool Returns `true` if `self` has no elements in common with `other`. This is equivalent to checking for an empty intersection. ##### Examples ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let mut b = HashSet::new(); assert_eq!(a.is_disjoint(&b), true); b.insert(4); assert_eq!(a.is_disjoint(&b), true); b.insert(1); assert_eq!(a.is_disjoint(&b), false); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#842-844)#### pub fn is\_subset(&self, other: &HashSet<T, S>) -> bool Returns `true` if the set is a subset of another, i.e., `other` contains at least all the values in `self`. ##### Examples ``` use std::collections::HashSet; let sup = HashSet::from([1, 2, 3]); let mut set = HashSet::new(); assert_eq!(set.is_subset(&sup), true); set.insert(2); assert_eq!(set.is_subset(&sup), true); set.insert(4); assert_eq!(set.is_subset(&sup), false); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#868-870)#### pub fn is\_superset(&self, other: &HashSet<T, S>) -> bool Returns `true` if the set is a superset of another, i.e., `self` contains at least all the values in `other`. ##### Examples ``` use std::collections::HashSet; let sub = HashSet::from([1, 2]); let mut set = HashSet::new(); assert_eq!(set.is_superset(&sub), false); set.insert(0); set.insert(1); assert_eq!(set.is_superset(&sub), false); set.insert(2); assert_eq!(set.is_superset(&sub), true); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#892-894)#### pub fn insert(&mut self, value: T) -> bool Adds a value to the set. Returns whether the value was newly inserted. That is: * If the set did not previously contain this value, `true` is returned. * If the set already contained this value, `false` is returned. ##### Examples ``` use std::collections::HashSet; let mut set = HashSet::new(); assert_eq!(set.insert(2), true); assert_eq!(set.insert(2), false); assert_eq!(set.len(), 1); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#913-915)1.9.0 · #### pub fn replace(&mut self, value: T) -> Option<T> Adds a value to the set, replacing the existing value, if any, that is equal to the given one. Returns the replaced value. ##### Examples ``` use std::collections::HashSet; let mut set = HashSet::new(); set.insert(Vec::<i32>::new()); assert_eq!(set.get(&[][..]).unwrap().capacity(), 0); set.replace(Vec::with_capacity(10)); assert_eq!(set.get(&[][..]).unwrap().capacity(), 10); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#937-943)#### pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> boolwhere T: [Borrow](../../borrow/trait.borrow "trait std::borrow::Borrow")<Q>, Q: [Hash](../../hash/trait.hash "trait std::hash::Hash") + [Eq](../../cmp/trait.eq "trait std::cmp::Eq"), Removes a value from the set. Returns whether the value was present in the set. The value may be any borrowed form of the set’s value type, but [`Hash`](../../hash/trait.hash "Hash") and [`Eq`](../../cmp/trait.eq "Eq") on the borrowed form *must* match those for the value type. ##### Examples ``` use std::collections::HashSet; let mut set = HashSet::new(); set.insert(2); assert_eq!(set.remove(&2), true); assert_eq!(set.remove(&2), false); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#962-968)1.9.0 · #### pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>where T: [Borrow](../../borrow/trait.borrow "trait std::borrow::Borrow")<Q>, Q: [Hash](../../hash/trait.hash "trait std::hash::Hash") + [Eq](../../cmp/trait.eq "trait std::cmp::Eq"), Removes and returns the value in the set, if any, that is equal to the given one. The value may be any borrowed form of the set’s value type, but [`Hash`](../../hash/trait.hash "Hash") and [`Eq`](../../cmp/trait.eq "Eq") on the borrowed form *must* match those for the value type. ##### Examples ``` use std::collections::HashSet; let mut set = HashSet::from([1, 2, 3]); assert_eq!(set.take(&2), Some(2)); assert_eq!(set.take(&2), None); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1156-1186)### impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash") + [Clone](../../clone/trait.clone "trait std::clone::Clone"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher") + [Default](../../default/trait.default "trait std::default::Default"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1183-1185)#### fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`. ##### Examples ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let b = HashSet::from([2, 3, 4]); let set = &a & &b; let mut i = 0; let expected = [2, 3]; for x in &set { assert!(expected.contains(x)); i += 1; } assert_eq!(i, expected.len()); ``` #### type Output = HashSet<T, S> The resulting type after applying the `&` operator. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1123-1153)### impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash") + [Clone](../../clone/trait.clone "trait std::clone::Clone"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher") + [Default](../../default/trait.default "trait std::default::Default"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1150-1152)#### fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> Returns the union of `self` and `rhs` as a new `HashSet<T, S>`. ##### Examples ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let b = HashSet::from([3, 4, 5]); let set = &a | &b; let mut i = 0; let expected = [1, 2, 3, 4, 5]; for x in &set { assert!(expected.contains(x)); i += 1; } assert_eq!(i, expected.len()); ``` #### type Output = HashSet<T, S> The resulting type after applying the `|` operator. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1189-1219)### impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash") + [Clone](../../clone/trait.clone "trait std::clone::Clone"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher") + [Default](../../default/trait.default "trait std::default::Default"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1216-1218)#### fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`. ##### Examples ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let b = HashSet::from([3, 4, 5]); let set = &a ^ &b; let mut i = 0; let expected = [1, 2, 4, 5]; for x in &set { assert!(expected.contains(x)); i += 1; } assert_eq!(i, expected.len()); ``` #### type Output = HashSet<T, S> The resulting type after applying the `^` operator. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#972-986)### impl<T, S> Clone for HashSet<T, S>where T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), S: [Clone](../../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#978-980)#### fn clone(&self) -> Self Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#983-985)#### fn clone\_from(&mut self, other: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1012-1019)### impl<T, S> Debug for HashSet<T, S>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1016-1018)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1111-1120)### impl<T, S> Default for HashSet<T, S>where S: [Default](../../default/trait.default "trait std::default::Default"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1117-1119)#### fn default() -> HashSet<T, S> Creates an empty `HashSet<T, S>` with the `Default` value for the hasher. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1089-1108)1.4.0 · ### impl<'a, T, S> Extend<&'a T> for HashSet<T, S>where T: 'a + [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash") + [Copy](../../marker/trait.copy "trait std::marker::Copy"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1095-1097)#### fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) Extends a collection with the contents of an iterator. [Read more](../../iter/trait.extend#tymethod.extend) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1100-1102)#### fn extend\_one(&mut self, item: &'a T) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Extends a collection with exactly one element. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1105-1107)#### fn extend\_reserve(&mut self, additional: usize) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Reserves capacity in a collection for the given number of additional elements. [Read more](../../iter/trait.extend#method.extend_reserve) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1067-1086)### impl<T, S> Extend<T> for HashSet<T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1073-1075)#### fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) Extends a collection with the contents of an iterator. [Read more](../../iter/trait.extend#tymethod.extend) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1078-1080)#### fn extend\_one(&mut self, item: T) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Extends a collection with exactly one element. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1083-1085)#### fn extend\_reserve(&mut self, additional: usize) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Reserves capacity in a collection for the given number of additional elements. [Read more](../../iter/trait.extend#method.extend_reserve) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1048-1064)1.56.0 · ### impl<T, const N: usize> From<[T; N]> for HashSet<T, RandomState>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1061-1063)#### fn from(arr: [T; N]) -> Self ##### Examples ``` use std::collections::HashSet; let set1 = HashSet::from([1, 2, 3, 4]); let set2: HashSet<_> = [1, 2, 3, 4].into(); assert_eq!(set1, set2); ``` [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1022-1033)### impl<T, S> FromIterator<T> for HashSet<T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher") + [Default](../../default/trait.default "trait std::default::Default"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1028-1032)#### fn from\_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> Creates a value from an iterator. [Read more](../../iter/trait.fromiterator#tymethod.from_iter) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1446-1455)### impl<'a, T, S> IntoIterator for &'a HashSet<T, S> #### type Item = &'a T The type of the elements being iterated over. #### type IntoIter = Iter<'a, T> Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1452-1454)#### fn into\_iter(self) -> Iter<'a, T> Notable traits for [Iter](struct.iter "struct std::collections::hash_set::Iter")<'a, K> ``` impl<'a, K> Iterator for Iter<'a, K> type Item = &'a K; ``` Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1458-1487)### impl<T, S> IntoIterator for HashSet<T, S> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1484-1486)#### fn into\_iter(self) -> IntoIter<T> Notable traits for [IntoIter](struct.intoiter "struct std::collections::hash_set::IntoIter")<K> ``` impl<K> Iterator for IntoIter<K> type Item = K; ``` Creates a consuming iterator, that is, one that moves each value out of the set in arbitrary order. The set cannot be used after calling this. ##### Examples ``` use std::collections::HashSet; let mut set = HashSet::new(); set.insert("a".to_string()); set.insert("b".to_string()); // Not possible to collect to a Vec<String> with a regular `.iter()`. let v: Vec<String> = set.into_iter().collect(); // Will print in an arbitrary order. for x in &v { println!("{x}"); } ``` #### type Item = T The type of the elements being iterated over. #### type IntoIter = IntoIter<T> Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#989-1001)### impl<T, S> PartialEq<HashSet<T, S>> for HashSet<T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#994-1000)#### fn eq(&self, other: &HashSet<T, S>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1222-1252)### impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash") + [Clone](../../clone/trait.clone "trait std::clone::Clone"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher") + [Default](../../default/trait.default "trait std::default::Default"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1249-1251)#### fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`. ##### Examples ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let b = HashSet::from([3, 4, 5]); let set = &a - &b; let mut i = 0; let expected = [1, 2]; for x in &set { assert!(expected.contains(x)); i += 1; } assert_eq!(i, expected.len()); ``` #### type Output = HashSet<T, S> The resulting type after applying the `-` operator. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1004-1009)### impl<T, S> Eq for HashSet<T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), Auto Trait Implementations -------------------------- ### impl<T, S> RefUnwindSafe for HashSet<T, S>where S: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<T, S> Send for HashSet<T, S>where S: [Send](../../marker/trait.send "trait std::marker::Send"), T: [Send](../../marker/trait.send "trait std::marker::Send"), ### impl<T, S> Sync for HashSet<T, S>where S: [Sync](../../marker/trait.sync "trait std::marker::Sync"), T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<T, S> Unpin for HashSet<T, S>where S: [Unpin](../../marker/trait.unpin "trait std::marker::Unpin"), T: [Unpin](../../marker/trait.unpin "trait std::marker::Unpin"), ### impl<T, S> UnwindSafe for HashSet<T, S>where S: [UnwindSafe](../../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), T: [UnwindSafe](../../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::hash_set::Union Struct std::collections::hash\_set::Union ========================================= ``` pub struct Union<'a, T: 'a, S: 'a> { /* private fields */ } ``` A lazy iterator producing elements in the union of `HashSet`s. This `struct` is created by the [`union`](struct.hashset#method.union) method on [`HashSet`](struct.hashset "HashSet"). See its documentation for more. Examples -------- ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let b = HashSet::from([4, 2, 3, 4]); let mut union_iter = a.union(&b); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1766-1771)### impl<T, S> Clone for Union<'\_, T, S> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1768-1770)#### fn clone(&self) -> Self Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1782-1790)1.16.0 · ### impl<T, S> Debug for Union<'\_, T, S>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug") + [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1787-1789)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1793-1808)### impl<'a, T, S> Iterator for Union<'a, T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), #### type Item = &'a T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1801-1803)#### fn next(&mut self) -> Option<&'a T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1805-1807)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)#### fn cycle(self) -> Cycle<Self>where Self: [Clone](../../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1774-1779)1.26.0 · ### impl<T, S> FusedIterator for Union<'\_, T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), Auto Trait Implementations -------------------------- ### impl<'a, T, S> RefUnwindSafe for Union<'a, T, S>where S: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T, S> Send for Union<'a, T, S>where S: [Sync](../../marker/trait.sync "trait std::marker::Sync"), T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T, S> Sync for Union<'a, T, S>where S: [Sync](../../marker/trait.sync "trait std::marker::Sync"), T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T, S> Unpin for Union<'a, T, S> ### impl<'a, T, S> UnwindSafe for Union<'a, T, S>where S: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::hash_set::IntoIter Struct std::collections::hash\_set::IntoIter ============================================ ``` pub struct IntoIter<K> { /* private fields */ } ``` An owning iterator over the items of a `HashSet`. This `struct` is created by the [`into_iter`](../../iter/trait.intoiterator#tymethod.into_iter) method on [`HashSet`](struct.hashset "HashSet") (provided by the [`IntoIterator`](../../iter/trait.intoiterator) trait). See its documentation for more. Examples -------- ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let mut iter = a.into_iter(); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1550-1554)1.16.0 · ### impl<K: Debug> Debug for IntoIter<K> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1551-1553)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1540-1545)### impl<K> ExactSizeIterator for IntoIter<K> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1542-1544)#### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#138)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1527-1538)### impl<K> Iterator for IntoIter<K> #### type Item = K The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1531-1533)#### fn next(&mut self) -> Option<K> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1535-1537)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1547)1.26.0 · ### impl<K> FusedIterator for IntoIter<K> Auto Trait Implementations -------------------------- ### impl<K> RefUnwindSafe for IntoIter<K>where K: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<K> Send for IntoIter<K>where K: [Send](../../marker/trait.send "trait std::marker::Send"), ### impl<K> Sync for IntoIter<K>where K: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<K> Unpin for IntoIter<K>where K: [Unpin](../../marker/trait.unpin "trait std::marker::Unpin"), ### impl<K> UnwindSafe for IntoIter<K>where K: [UnwindSafe](../../panic/trait.unwindsafe "trait std::panic::UnwindSafe") + [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::hash_set::Difference Struct std::collections::hash\_set::Difference ============================================== ``` pub struct Difference<'a, T: 'a, S: 'a> { /* private fields */ } ``` A lazy iterator producing elements in the difference of `HashSet`s. This `struct` is created by the [`difference`](struct.hashset#method.difference) method on [`HashSet`](struct.hashset "HashSet"). See its documentation for more. Examples -------- ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let b = HashSet::from([4, 2, 3, 4]); let mut difference = a.difference(&b); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1669-1674)### impl<T, S> Clone for Difference<'\_, T, S> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1671-1673)#### fn clone(&self) -> Self Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1710-1718)1.16.0 · ### impl<T, S> Debug for Difference<'\_, T, S>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug") + [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1715-1717)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1677-1699)### impl<'a, T, S> Iterator for Difference<'a, T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), #### type Item = &'a T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1685-1692)#### fn next(&mut self) -> Option<&'a T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1695-1698)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)#### fn cycle(self) -> Cycle<Self>where Self: [Clone](../../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1702-1707)1.26.0 · ### impl<T, S> FusedIterator for Difference<'\_, T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), Auto Trait Implementations -------------------------- ### impl<'a, T, S> RefUnwindSafe for Difference<'a, T, S>where S: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T, S> Send for Difference<'a, T, S>where S: [Sync](../../marker/trait.sync "trait std::marker::Sync"), T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T, S> Sync for Difference<'a, T, S>where S: [Sync](../../marker/trait.sync "trait std::marker::Sync"), T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T, S> Unpin for Difference<'a, T, S> ### impl<'a, T, S> UnwindSafe for Difference<'a, T, S>where S: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::hash_set::DrainFilter Struct std::collections::hash\_set::DrainFilter =============================================== ``` pub struct DrainFilter<'a, K, F>where    F: FnMut(&K) -> bool,{ /* private fields */ } ``` 🔬This is a nightly-only experimental API. (`hash_drain_filter` [#59618](https://github.com/rust-lang/rust/issues/59618)) A draining, filtering iterator over the items of a `HashSet`. This `struct` is created by the [`drain_filter`](struct.hashset#method.drain_filter) method on [`HashSet`](struct.hashset "HashSet"). Examples -------- ``` #![feature(hash_drain_filter)] use std::collections::HashSet; let mut a = HashSet::from([1, 2, 3]); let mut drain_filtered = a.drain_filter(|v| v % 2 == 0); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1607-1614)### impl<'a, K, F> Debug for DrainFilter<'a, K, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)K) -> [bool](../../primitive.bool), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1611-1613)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1587-1601)### impl<K, F> Iterator for DrainFilter<'\_, K, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)K) -> [bool](../../primitive.bool), #### type Item = K The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1594-1596)#### fn next(&mut self) -> Option<K> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1598-1600)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1604)### impl<K, F> FusedIterator for DrainFilter<'\_, K, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)K) -> [bool](../../primitive.bool), Auto Trait Implementations -------------------------- ### impl<'a, K, F> RefUnwindSafe for DrainFilter<'a, K, F>where F: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), K: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, K, F> Send for DrainFilter<'a, K, F>where F: [Send](../../marker/trait.send "trait std::marker::Send"), K: [Send](../../marker/trait.send "trait std::marker::Send"), ### impl<'a, K, F> Sync for DrainFilter<'a, K, F>where F: [Sync](../../marker/trait.sync "trait std::marker::Sync"), K: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, K, F> Unpin for DrainFilter<'a, K, F>where F: [Unpin](../../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, K, F> !UnwindSafe for DrainFilter<'a, K, F> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::hash_set::Drain Struct std::collections::hash\_set::Drain ========================================= ``` pub struct Drain<'a, K: 'a> { /* private fields */ } ``` A draining iterator over the items of a `HashSet`. This `struct` is created by the [`drain`](struct.hashset#method.drain) method on [`HashSet`](struct.hashset "HashSet"). See its documentation for more. Examples -------- ``` use std::collections::HashSet; let mut a = HashSet::from([1, 2, 3]); let mut drain = a.drain(); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1580-1584)1.16.0 · ### impl<K: Debug> Debug for Drain<'\_, K> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1581-1583)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1570-1575)### impl<K> ExactSizeIterator for Drain<'\_, K> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1572-1574)#### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#138)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1557-1568)### impl<'a, K> Iterator for Drain<'a, K> #### type Item = K The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1561-1563)#### fn next(&mut self) -> Option<K> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1565-1567)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1577)1.26.0 · ### impl<K> FusedIterator for Drain<'\_, K> Auto Trait Implementations -------------------------- ### impl<'a, K> RefUnwindSafe for Drain<'a, K>where K: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, K> Send for Drain<'a, K>where K: [Send](../../marker/trait.send "trait std::marker::Send"), ### impl<'a, K> Sync for Drain<'a, K>where K: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, K> Unpin for Drain<'a, K>where K: [Unpin](../../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, K> UnwindSafe for Drain<'a, K>where K: [UnwindSafe](../../panic/trait.unwindsafe "trait std::panic::UnwindSafe") + [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::hash_set::SymmetricDifference Struct std::collections::hash\_set::SymmetricDifference ======================================================= ``` pub struct SymmetricDifference<'a, T: 'a, S: 'a> { /* private fields */ } ``` A lazy iterator producing elements in the symmetric difference of `HashSet`s. This `struct` is created by the [`symmetric_difference`](struct.hashset#method.symmetric_difference) method on [`HashSet`](struct.hashset "HashSet"). See its documentation for more. Examples -------- ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let b = HashSet::from([4, 2, 3, 4]); let mut intersection = a.symmetric_difference(&b); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1721-1726)### impl<T, S> Clone for SymmetricDifference<'\_, T, S> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1723-1725)#### fn clone(&self) -> Self Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1755-1763)1.16.0 · ### impl<T, S> Debug for SymmetricDifference<'\_, T, S>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug") + [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1760-1762)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1729-1744)### impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), #### type Item = &'a T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1737-1739)#### fn next(&mut self) -> Option<&'a T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1741-1743)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)#### fn cycle(self) -> Cycle<Self>where Self: [Clone](../../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1747-1752)1.26.0 · ### impl<T, S> FusedIterator for SymmetricDifference<'\_, T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), Auto Trait Implementations -------------------------- ### impl<'a, T, S> RefUnwindSafe for SymmetricDifference<'a, T, S>where S: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T, S> Send for SymmetricDifference<'a, T, S>where S: [Sync](../../marker/trait.sync "trait std::marker::Sync"), T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T, S> Sync for SymmetricDifference<'a, T, S>where S: [Sync](../../marker/trait.sync "trait std::marker::Sync"), T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T, S> Unpin for SymmetricDifference<'a, T, S> ### impl<'a, T, S> UnwindSafe for SymmetricDifference<'a, T, S>where S: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::hash_set::Iter Struct std::collections::hash\_set::Iter ======================================== ``` pub struct Iter<'a, K: 'a> { /* private fields */ } ``` An iterator over the items of a `HashSet`. This `struct` is created by the [`iter`](struct.hashset#method.iter) method on [`HashSet`](struct.hashset "HashSet"). See its documentation for more. Examples -------- ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let mut iter = a.iter(); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1490-1495)### impl<K> Clone for Iter<'\_, K> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1492-1494)#### fn clone(&self) -> Self Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1520-1524)1.16.0 · ### impl<K: Debug> Debug for Iter<'\_, K> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1521-1523)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1510-1515)### impl<K> ExactSizeIterator for Iter<'\_, K> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1512-1514)#### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#138)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1497-1508)### impl<'a, K> Iterator for Iter<'a, K> #### type Item = &'a K The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1501-1503)#### fn next(&mut self) -> Option<&'a K> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1505-1507)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)#### fn cycle(self) -> Cycle<Self>where Self: [Clone](../../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1517)1.26.0 · ### impl<K> FusedIterator for Iter<'\_, K> Auto Trait Implementations -------------------------- ### impl<'a, K> RefUnwindSafe for Iter<'a, K>where K: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, K> Send for Iter<'a, K>where K: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, K> Sync for Iter<'a, K>where K: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, K> Unpin for Iter<'a, K> ### impl<'a, K> UnwindSafe for Iter<'a, K>where K: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::hash_set::Intersection Struct std::collections::hash\_set::Intersection ================================================ ``` pub struct Intersection<'a, T: 'a, S: 'a> { /* private fields */ } ``` A lazy iterator producing elements in the intersection of `HashSet`s. This `struct` is created by the [`intersection`](struct.hashset#method.intersection) method on [`HashSet`](struct.hashset "HashSet"). See its documentation for more. Examples -------- ``` use std::collections::HashSet; let a = HashSet::from([1, 2, 3]); let b = HashSet::from([4, 2, 3, 4]); let mut intersection = a.intersection(&b); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1617-1622)### impl<T, S> Clone for Intersection<'\_, T, S> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1619-1621)#### fn clone(&self) -> Self Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1650-1658)1.16.0 · ### impl<T, S> Debug for Intersection<'\_, T, S>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug") + [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1655-1657)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1625-1647)### impl<'a, T, S> Iterator for Intersection<'a, T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), #### type Item = &'a T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1633-1640)#### fn next(&mut self) -> Option<&'a T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1643-1646)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)#### fn cycle(self) -> Cycle<Self>where Self: [Clone](../../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1661-1666)1.26.0 · ### impl<T, S> FusedIterator for Intersection<'\_, T, S>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../../hash/trait.hash "trait std::hash::Hash"), S: [BuildHasher](../../hash/trait.buildhasher "trait std::hash::BuildHasher"), Auto Trait Implementations -------------------------- ### impl<'a, T, S> RefUnwindSafe for Intersection<'a, T, S>where S: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T, S> Send for Intersection<'a, T, S>where S: [Sync](../../marker/trait.sync "trait std::marker::Sync"), T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T, S> Sync for Intersection<'a, T, S>where S: [Sync](../../marker/trait.sync "trait std::marker::Sync"), T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T, S> Unpin for Intersection<'a, T, S> ### impl<'a, T, S> UnwindSafe for Intersection<'a, T, S>where S: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Module std::collections::vec_deque Module std::collections::vec\_deque =================================== A double-ended queue (deque) implemented with a growable ring buffer. This queue has *O*(1) amortized inserts and removals from both ends of the container. It also has *O*(1) indexing like a vector. The contained elements are not required to be copyable, and the queue will be sendable if the contained type is sendable. Structs ------- [Drain](struct.drain "std::collections::vec_deque::Drain struct") A draining iterator over the elements of a `VecDeque`. [IntoIter](struct.intoiter "std::collections::vec_deque::IntoIter struct") An owning iterator over the elements of a `VecDeque`. [Iter](struct.iter "std::collections::vec_deque::Iter struct") An iterator over the elements of a `VecDeque`. [IterMut](struct.itermut "std::collections::vec_deque::IterMut struct") A mutable iterator over the elements of a `VecDeque`. [VecDeque](struct.vecdeque "std::collections::vec_deque::VecDeque struct") A double-ended queue implemented with a growable ring buffer. rust Struct std::collections::vec_deque::IterMut Struct std::collections::vec\_deque::IterMut ============================================ ``` pub struct IterMut<'a, T>where    T: 'a,{ /* private fields */ } ``` A mutable iterator over the elements of a `VecDeque`. This `struct` is created by the [`iter_mut`](../struct.vecdeque#method.iter_mut) method on [`super::VecDeque`](../struct.vecdeque "super::VecDeque"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#41)1.17.0 · ### impl<T> Debug for IterMut<'\_, T>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#42)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#114)### impl<'a, T> DoubleEndedIterator for IterMut<'a, T> [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#116)#### fn next\_back(&mut self) -> Option<&'a mut T> Removes and returns an element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#128-130)#### fn rfold<Acc, F>(self, accum: Acc, f: F) -> Accwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Acc, <[IterMut](struct.itermut "struct std::collections::vec_deque::IterMut")<'a, T> as [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Acc, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#142)### impl<T> ExactSizeIterator for IterMut<'\_, T> [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#143)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#106)#### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#52)### impl<'a, T> Iterator for IterMut<'a, T> #### type Item = &'a mut T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#56)#### fn next(&mut self) -> Option<&'a mut T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#70)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#75-77)#### fn fold<Acc, F>(self, accum: Acc, f: F) -> Accwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Acc, <[IterMut](struct.itermut "struct std::collections::vec_deque::IterMut")<'a, T> as [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Acc, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#87)#### fn nth(&mut self, n: usize) -> Option<<IterMut<'a, T> as Iterator>::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#98)#### fn last(self) -> Option<&'a mut T> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../../primitive.reference) T>, P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2920-2923)#### fn rposition<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Self: [ExactSizeIterator](../../iter/trait.exactsizeiterator "trait std::iter::ExactSizeIterator") + [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Searches for an element in an iterator from the right, returning its index. [Read more](../../iter/trait.iterator#method.rposition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)#### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#149)1.26.0 · ### impl<T> FusedIterator for IterMut<'\_, T> [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#36)### impl<T> Send for IterMut<'\_, T>where T: [Send](../../marker/trait.send "trait std::marker::Send"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#38)### impl<T> Sync for IterMut<'\_, T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#152)### impl<T> TrustedLen for IterMut<'\_, T> Auto Trait Implementations -------------------------- ### impl<'a, T> RefUnwindSafe for IterMut<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T> Unpin for IterMut<'a, T> ### impl<'a, T> !UnwindSafe for IterMut<'a, T> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::vec_deque::IntoIter Struct std::collections::vec\_deque::IntoIter ============================================= ``` pub struct IntoIter<T, A = Global>where    A: Allocator,{ /* private fields */ } ``` An owning iterator over the elements of a `VecDeque`. This `struct` is created by the [`into_iter`](../struct.vecdeque#method.into_iter) method on [`VecDeque`](../struct.vecdeque "VecDeque") (provided by the [`IntoIterator`](../../iter/trait.intoiterator) trait). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/into_iter.rs.html#15)### impl<T, A> Clone for IntoIter<T, A>where T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), A: [Clone](../../clone/trait.clone "trait std::clone::Clone") + [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/into_iter.rs.html#15)#### fn clone(&self) -> IntoIter<T, A> Notable traits for [IntoIter](struct.intoiter "struct std::collections::vec_deque::IntoIter")<T, A> ``` impl<T, A> Iterator for IntoIter<T, A>where     A: Allocator, type Item = T; ``` Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/into_iter.rs.html#31)1.17.0 · ### impl<T, A> Debug for IntoIter<T, A>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/into_iter.rs.html#32)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/into_iter.rs.html#54)### impl<T, A> DoubleEndedIterator for IntoIter<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/into_iter.rs.html#56)#### fn next\_back(&mut self) -> Option<T> Removes and returns an element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/into_iter.rs.html#62)### impl<T, A> ExactSizeIterator for IntoIter<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/into_iter.rs.html#63)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#106)#### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/into_iter.rs.html#38)### impl<T, A> Iterator for IntoIter<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), #### type Item = T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/into_iter.rs.html#42)#### fn next(&mut self) -> Option<T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/into_iter.rs.html#47)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../../primitive.reference) T>, P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2920-2923)#### fn rposition<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Self: [ExactSizeIterator](../../iter/trait.exactsizeiterator "trait std::iter::ExactSizeIterator") + [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Searches for an element in an iterator from the right, returning its index. [Read more](../../iter/trait.iterator#method.rposition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)#### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/into_iter.rs.html#69)1.26.0 · ### impl<T, A> FusedIterator for IntoIter<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/into_iter.rs.html#72)### impl<T, A> TrustedLen for IntoIter<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), Auto Trait Implementations -------------------------- ### impl<T, A> RefUnwindSafe for IntoIter<T, A>where A: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<T, A> Send for IntoIter<T, A>where A: [Send](../../marker/trait.send "trait std::marker::Send"), T: [Send](../../marker/trait.send "trait std::marker::Send"), ### impl<T, A> Sync for IntoIter<T, A>where A: [Sync](../../marker/trait.sync "trait std::marker::Sync"), T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<T, A> Unpin for IntoIter<T, A>where A: [Unpin](../../marker/trait.unpin "trait std::marker::Unpin"), T: [Unpin](../../marker/trait.unpin "trait std::marker::Unpin"), ### impl<T, A> UnwindSafe for IntoIter<T, A>where A: [UnwindSafe](../../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), T: [UnwindSafe](../../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::vec_deque::VecDeque Struct std::collections::vec\_deque::VecDeque ============================================= ``` pub struct VecDeque<T, A = Global>where    A: Allocator,{ /* private fields */ } ``` A double-ended queue implemented with a growable ring buffer. The “default” usage of this type as a queue is to use [`push_back`](../struct.vecdeque#method.push_back) to add to the queue, and [`pop_front`](../struct.vecdeque#method.pop_front) to remove from the queue. [`extend`](../struct.vecdeque#method.extend) and [`append`](../struct.vecdeque#method.append) push onto the back in this manner, and iterating over `VecDeque` goes front to back. A `VecDeque` with a known list of items can be initialized from an array: ``` use std::collections::VecDeque; let deq = VecDeque::from([-1, 0, 1]); ``` Since `VecDeque` is a ring buffer, its elements are not necessarily contiguous in memory. If you want to access the elements as a single slice, such as for efficient sorting, you can use [`make_contiguous`](../struct.vecdeque#method.make_contiguous). It rotates the `VecDeque` so that its elements do not wrap, and returns a mutable slice to the now-contiguous element sequence. Implementations --------------- [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#520)### impl<T> VecDeque<T, Global> [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#533)#### pub fn new() -> VecDeque<T, Global> Notable traits for [VecDeque](../struct.vecdeque "struct std::collections::VecDeque")<[u8](../../primitive.u8), A> ``` impl<A: Allocator> Read for VecDeque<u8, A> impl<A: Allocator> Write for VecDeque<u8, A> ``` Creates an empty deque. ##### Examples ``` use std::collections::VecDeque; let deque: VecDeque<u32> = VecDeque::new(); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#549)#### pub fn with\_capacity(capacity: usize) -> VecDeque<T, Global> Notable traits for [VecDeque](../struct.vecdeque "struct std::collections::VecDeque")<[u8](../../primitive.u8), A> ``` impl<A: Allocator> Read for VecDeque<u8, A> impl<A: Allocator> Write for VecDeque<u8, A> ``` Creates an empty deque with space for at least `capacity` elements. ##### Examples ``` use std::collections::VecDeque; let deque: VecDeque<u32> = VecDeque::with_capacity(10); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#554)### impl<T, A> VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#566)#### pub fn new\_in(alloc: A) -> VecDeque<T, A> Notable traits for [VecDeque](../struct.vecdeque "struct std::collections::VecDeque")<[u8](../../primitive.u8), A> ``` impl<A: Allocator> Read for VecDeque<u8, A> impl<A: Allocator> Write for VecDeque<u8, A> ``` 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838)) Creates an empty deque. ##### Examples ``` use std::collections::VecDeque; let deque: VecDeque<u32> = VecDeque::new(); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#580)#### pub fn with\_capacity\_in(capacity: usize, alloc: A) -> VecDeque<T, A> Notable traits for [VecDeque](../struct.vecdeque "struct std::collections::VecDeque")<[u8](../../primitive.u8), A> ``` impl<A: Allocator> Read for VecDeque<u8, A> impl<A: Allocator> Write for VecDeque<u8, A> ``` 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838)) Creates an empty deque with space for at least `capacity` elements. ##### Examples ``` use std::collections::VecDeque; let deque: VecDeque<u32> = VecDeque::with_capacity(10); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#604)#### pub fn get(&self, index: usize) -> Option<&T> Provides a reference to the element at the given index. Element at index 0 is the front of the queue. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(3); buf.push_back(4); buf.push_back(5); assert_eq!(buf.get(1), Some(&4)); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#633)#### pub fn get\_mut(&mut self, index: usize) -> Option<&mut T> Provides a mutable reference to the element at the given index. Element at index 0 is the front of the queue. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(3); buf.push_back(4); buf.push_back(5); if let Some(elem) = buf.get_mut(1) { *elem = 7; } assert_eq!(buf[1], 7); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#666)#### pub fn swap(&mut self, i: usize, j: usize) Swaps elements at indices `i` and `j`. `i` and `j` may be equal. Element at index 0 is the front of the queue. ##### Panics Panics if either index is out of bounds. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(3); buf.push_back(4); buf.push_back(5); assert_eq!(buf, [3, 4, 5]); buf.swap(0, 2); assert_eq!(buf, [5, 4, 3]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#687)#### pub fn capacity(&self) -> usize Returns the number of elements the deque can hold without reallocating. ##### Examples ``` use std::collections::VecDeque; let buf: VecDeque<i32> = VecDeque::with_capacity(10); assert!(buf.capacity() >= 10); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#714)#### pub fn reserve\_exact(&mut self, additional: usize) Reserves the minimum capacity for at least `additional` more elements to be inserted in the given deque. Does nothing if the capacity is already sufficient. Note that the allocator may give the collection more space than it requests. Therefore capacity can not be relied upon to be precisely minimal. Prefer [`reserve`](../struct.vecdeque#method.reserve) if future insertions are expected. ##### Panics Panics if the new capacity overflows `usize`. ##### Examples ``` use std::collections::VecDeque; let mut buf: VecDeque<i32> = [1].into(); buf.reserve_exact(10); assert!(buf.capacity() >= 11); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#735)#### pub fn reserve(&mut self, additional: usize) Reserves capacity for at least `additional` more elements to be inserted in the given deque. The collection may reserve more space to speculatively avoid frequent reallocations. ##### Panics Panics if the new capacity overflows `usize`. ##### Examples ``` use std::collections::VecDeque; let mut buf: VecDeque<i32> = [1].into(); buf.reserve(10); assert!(buf.capacity() >= 11); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#789)1.57.0 · #### pub fn try\_reserve\_exact( &mut self, additional: usize) -> Result<(), TryReserveError> Tries to reserve the minimum capacity for at least `additional` more elements to be inserted in the given deque. After calling `try_reserve_exact`, capacity will be greater than or equal to `self.len() + additional` if it returns `Ok(())`. Does nothing if the capacity is already sufficient. Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer [`try_reserve`](../struct.vecdeque#method.try_reserve) if future insertions are expected. ##### Errors If the capacity overflows `usize`, or the allocator reports a failure, then an error is returned. ##### Examples ``` use std::collections::TryReserveError; use std::collections::VecDeque; fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> { let mut output = VecDeque::new(); // Pre-reserve the memory, exiting if we can't output.try_reserve_exact(data.len())?; // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work output.extend(data.iter().map(|&val| { val * 2 + 5 // very complicated })); Ok(output) } ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#827)1.57.0 · #### pub fn try\_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> Tries to reserve capacity for at least `additional` more elements to be inserted in the given deque. The collection may reserve more space to speculatively avoid frequent reallocations. After calling `try_reserve`, capacity will be greater than or equal to `self.len() + additional` if it returns `Ok(())`. Does nothing if capacity is already sufficient. This method preserves the contents even if an error occurs. ##### Errors If the capacity overflows `usize`, or the allocator reports a failure, then an error is returned. ##### Examples ``` use std::collections::TryReserveError; use std::collections::VecDeque; fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> { let mut output = VecDeque::new(); // Pre-reserve the memory, exiting if we can't output.try_reserve(data.len())?; // Now we know this can't OOM in the middle of our complex work output.extend(data.iter().map(|&val| { val * 2 + 5 // very complicated })); Ok(output) } ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#861)1.5.0 · #### pub fn shrink\_to\_fit(&mut self) Shrinks the capacity of the deque as much as possible. It will drop down as close as possible to the length but the allocator may still inform the deque that there is space for a few more elements. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::with_capacity(15); buf.extend(0..4); assert_eq!(buf.capacity(), 15); buf.shrink_to_fit(); assert!(buf.capacity() >= 4); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#886)1.56.0 · #### pub fn shrink\_to(&mut self, min\_capacity: usize) Shrinks the capacity of the deque with a lower bound. The capacity will remain at least as large as both the length and the supplied value. If the current capacity is less than the lower limit, this is a no-op. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::with_capacity(15); buf.extend(0..4); assert_eq!(buf.capacity(), 15); buf.shrink_to(6); assert!(buf.capacity() >= 6); buf.shrink_to(0); assert!(buf.capacity() >= 4); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#968)1.16.0 · #### pub fn truncate(&mut self, len: usize) Shortens the deque, keeping the first `len` elements and dropping the rest. If `len` is greater than the deque’s current length, this has no effect. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(5); buf.push_back(10); buf.push_back(15); assert_eq!(buf, [5, 10, 15]); buf.truncate(1); assert_eq!(buf, [5]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1015)#### pub fn allocator(&self) -> &A 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838)) Returns a reference to the underlying allocator. [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1035)#### pub fn iter(&self) -> Iter<'\_, T> Notable traits for [Iter](struct.iter "struct std::collections::vec_deque::Iter")<'a, T> ``` impl<'a, T> Iterator for Iter<'a, T> type Item = &'a T; ``` Returns a front-to-back iterator. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(5); buf.push_back(3); buf.push_back(4); let b: &[_] = &[&5, &3, &4]; let c: Vec<&i32> = buf.iter().collect(); assert_eq!(&c[..], b); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1057)#### pub fn iter\_mut(&mut self) -> IterMut<'\_, T> Notable traits for [IterMut](struct.itermut "struct std::collections::vec_deque::IterMut")<'a, T> ``` impl<'a, T> Iterator for IterMut<'a, T> type Item = &'a mut T; ``` Returns a front-to-back iterator that returns mutable references. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(5); buf.push_back(3); buf.push_back(4); for num in buf.iter_mut() { *num = *num - 2; } let b: &[_] = &[&mut 3, &mut 1, &mut 2]; assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1093)1.5.0 · #### pub fn as\_slices(&self) -> (&[T], &[T]) Returns a pair of slices which contain, in order, the contents of the deque. If [`make_contiguous`](../struct.vecdeque#method.make_contiguous) was previously called, all elements of the deque will be in the first slice and the second slice will be empty. ##### Examples ``` use std::collections::VecDeque; let mut deque = VecDeque::new(); deque.push_back(0); deque.push_back(1); deque.push_back(2); assert_eq!(deque.as_slices(), (&[0, 1, 2][..], &[][..])); deque.push_front(10); deque.push_front(9); assert_eq!(deque.as_slices(), (&[9, 10][..], &[0, 1, 2][..])); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1131)1.5.0 · #### pub fn as\_mut\_slices(&mut self) -> (&mut [T], &mut [T]) Returns a pair of slices which contain, in order, the contents of the deque. If [`make_contiguous`](../struct.vecdeque#method.make_contiguous) was previously called, all elements of the deque will be in the first slice and the second slice will be empty. ##### Examples ``` use std::collections::VecDeque; let mut deque = VecDeque::new(); deque.push_back(0); deque.push_back(1); deque.push_front(10); deque.push_front(9); deque.as_mut_slices().0[0] = 42; deque.as_mut_slices().1[0] = 24; assert_eq!(deque.as_slices(), (&[42, 10][..], &[24, 1][..])); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1157)#### pub fn len(&self) -> usize Returns the number of elements in the deque. ##### Examples ``` use std::collections::VecDeque; let mut deque = VecDeque::new(); assert_eq!(deque.len(), 0); deque.push_back(1); assert_eq!(deque.len(), 1); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1174)#### pub fn is\_empty(&self) -> bool Returns `true` if the deque is empty. ##### Examples ``` use std::collections::VecDeque; let mut deque = VecDeque::new(); assert!(deque.is_empty()); deque.push_front(1); assert!(!deque.is_empty()); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1210-1212)1.51.0 · #### pub fn range<R>(&self, range: R) -> Iter<'\_, T>where R: [RangeBounds](../../ops/trait.rangebounds "trait std::ops::RangeBounds")<[usize](../../primitive.usize)>, Notable traits for [Iter](struct.iter "struct std::collections::vec_deque::Iter")<'a, T> ``` impl<'a, T> Iterator for Iter<'a, T> type Item = &'a T; ``` Creates an iterator that covers the specified range in the deque. ##### Panics Panics if the starting point is greater than the end point or if the end point is greater than the length of the deque. ##### Examples ``` use std::collections::VecDeque; let deque: VecDeque<_> = [1, 2, 3].into(); let range = deque.range(2..).copied().collect::<VecDeque<_>>(); assert_eq!(range, [3]); // A full range covers all contents let all = deque.range(..); assert_eq!(all.len(), 3); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1245-1247)1.51.0 · #### pub fn range\_mut<R>(&mut self, range: R) -> IterMut<'\_, T>where R: [RangeBounds](../../ops/trait.rangebounds "trait std::ops::RangeBounds")<[usize](../../primitive.usize)>, Notable traits for [IterMut](struct.itermut "struct std::collections::vec_deque::IterMut")<'a, T> ``` impl<'a, T> Iterator for IterMut<'a, T> type Item = &'a mut T; ``` Creates an iterator that covers the specified mutable range in the deque. ##### Panics Panics if the starting point is greater than the end point or if the end point is greater than the length of the deque. ##### Examples ``` use std::collections::VecDeque; let mut deque: VecDeque<_> = [1, 2, 3].into(); for v in deque.range_mut(2..) { *v *= 2; } assert_eq!(deque, [1, 2, 6]); // A full range covers all contents for v in deque.range_mut(..) { *v *= 2; } assert_eq!(deque, [2, 4, 12]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1293-1295)1.6.0 · #### pub fn drain<R>(&mut self, range: R) -> Drain<'\_, T, A>where R: [RangeBounds](../../ops/trait.rangebounds "trait std::ops::RangeBounds")<[usize](../../primitive.usize)>, Notable traits for [Drain](struct.drain "struct std::collections::vec_deque::Drain")<'\_, T, A> ``` impl<T, A> Iterator for Drain<'_, T, A>where     A: Allocator, type Item = T; ``` Removes the specified range from the deque in bulk, returning all removed elements as an iterator. If the iterator is dropped before being fully consumed, it drops the remaining removed elements. The returned iterator keeps a mutable borrow on the queue to optimize its implementation. ##### Panics Panics if the starting point is greater than the end point or if the end point is greater than the length of the deque. ##### Leaking If the returned iterator goes out of scope without being dropped (due to [`mem::forget`](../../mem/fn.forget "mem::forget"), for example), the deque may have lost and leaked elements arbitrarily, including elements outside the range. ##### Examples ``` use std::collections::VecDeque; let mut deque: VecDeque<_> = [1, 2, 3].into(); let drained = deque.drain(2..).collect::<VecDeque<_>>(); assert_eq!(drained, [3]); assert_eq!(deque, [1, 2]); // A full range clears all contents, like `clear()` does deque.drain(..); assert!(deque.is_empty()); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1356)#### pub fn clear(&mut self) Clears the deque, removing all values. ##### Examples ``` use std::collections::VecDeque; let mut deque = VecDeque::new(); deque.push_back(1); deque.clear(); assert!(deque.is_empty()); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1383-1385)1.12.0 · #### pub fn contains(&self, x: &T) -> boolwhere T: [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<T>, Returns `true` if the deque contains an element equal to the given value. This operation is *O*(*n*). Note that if you have a sorted `VecDeque`, [`binary_search`](../struct.vecdeque#method.binary_search) may be faster. ##### Examples ``` use std::collections::VecDeque; let mut deque: VecDeque<u32> = VecDeque::new(); deque.push_back(0); deque.push_back(1); assert_eq!(deque.contains(&1), true); assert_eq!(deque.contains(&10), false); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1407)#### pub fn front(&self) -> Option<&T> Provides a reference to the front element, or `None` if the deque is empty. ##### Examples ``` use std::collections::VecDeque; let mut d = VecDeque::new(); assert_eq!(d.front(), None); d.push_back(1); d.push_back(2); assert_eq!(d.front(), Some(&1)); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1431)#### pub fn front\_mut(&mut self) -> Option<&mut T> Provides a mutable reference to the front element, or `None` if the deque is empty. ##### Examples ``` use std::collections::VecDeque; let mut d = VecDeque::new(); assert_eq!(d.front_mut(), None); d.push_back(1); d.push_back(2); match d.front_mut() { Some(x) => *x = 9, None => (), } assert_eq!(d.front(), Some(&9)); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1451)#### pub fn back(&self) -> Option<&T> Provides a reference to the back element, or `None` if the deque is empty. ##### Examples ``` use std::collections::VecDeque; let mut d = VecDeque::new(); assert_eq!(d.back(), None); d.push_back(1); d.push_back(2); assert_eq!(d.back(), Some(&2)); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1475)#### pub fn back\_mut(&mut self) -> Option<&mut T> Provides a mutable reference to the back element, or `None` if the deque is empty. ##### Examples ``` use std::collections::VecDeque; let mut d = VecDeque::new(); assert_eq!(d.back(), None); d.push_back(1); d.push_back(2); match d.back_mut() { Some(x) => *x = 9, None => (), } assert_eq!(d.back(), Some(&9)); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1496)#### pub fn pop\_front(&mut self) -> Option<T> Removes the first element and returns it, or `None` if the deque is empty. ##### Examples ``` use std::collections::VecDeque; let mut d = VecDeque::new(); d.push_back(1); d.push_back(2); assert_eq!(d.pop_front(), Some(1)); assert_eq!(d.pop_front(), Some(2)); assert_eq!(d.pop_front(), None); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1521)#### pub fn pop\_back(&mut self) -> Option<T> Removes the last element from the deque and returns it, or `None` if it is empty. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); assert_eq!(buf.pop_back(), None); buf.push_back(1); buf.push_back(3); assert_eq!(buf.pop_back(), Some(3)); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1544)#### pub fn push\_front(&mut self, value: T) Prepends an element to the deque. ##### Examples ``` use std::collections::VecDeque; let mut d = VecDeque::new(); d.push_front(1); d.push_front(2); assert_eq!(d.front(), Some(&2)); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1569)#### pub fn push\_back(&mut self, value: T) Appends an element to the back of the deque. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(1); buf.push_back(3); assert_eq!(3, *buf.back().unwrap()); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1611)1.5.0 · #### pub fn swap\_remove\_front(&mut self, index: usize) -> Option<T> Removes an element from anywhere in the deque and returns it, replacing it with the first element. This does not preserve ordering, but is *O*(1). Returns `None` if `index` is out of bounds. Element at index 0 is the front of the queue. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); assert_eq!(buf.swap_remove_front(0), None); buf.push_back(1); buf.push_back(2); buf.push_back(3); assert_eq!(buf, [1, 2, 3]); assert_eq!(buf.swap_remove_front(2), Some(3)); assert_eq!(buf, [2, 1]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1646)1.5.0 · #### pub fn swap\_remove\_back(&mut self, index: usize) -> Option<T> Removes an element from anywhere in the deque and returns it, replacing it with the last element. This does not preserve ordering, but is *O*(1). Returns `None` if `index` is out of bounds. Element at index 0 is the front of the queue. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); assert_eq!(buf.swap_remove_back(0), None); buf.push_back(1); buf.push_back(2); buf.push_back(3); assert_eq!(buf, [1, 2, 3]); assert_eq!(buf.swap_remove_back(0), Some(1)); assert_eq!(buf, [3, 2]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1680)1.5.0 · #### pub fn insert(&mut self, index: usize, value: T) Inserts an element at `index` within the deque, shifting all elements with indices greater than or equal to `index` towards the back. Element at index 0 is the front of the queue. ##### Panics Panics if `index` is greater than deque’s length ##### Examples ``` use std::collections::VecDeque; let mut vec_deque = VecDeque::new(); vec_deque.push_back('a'); vec_deque.push_back('b'); vec_deque.push_back('c'); assert_eq!(vec_deque, &['a', 'b', 'c']); vec_deque.insert(1, 'd'); assert_eq!(vec_deque, &['a', 'd', 'b', 'c']); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#1902)#### pub fn remove(&mut self, index: usize) -> Option<T> Removes and returns the element at `index` from the deque. Whichever end is closer to the removal point will be moved to make room, and all the affected elements will be moved to new positions. Returns `None` if `index` is out of bounds. Element at index 0 is the front of the queue. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(1); buf.push_back(2); buf.push_back(3); assert_eq!(buf, [1, 2, 3]); assert_eq!(buf.remove(1), Some(2)); assert_eq!(buf, [1, 3]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2084-2086)1.4.0 · #### pub fn split\_off(&mut self, at: usize) -> VecDeque<T, A>where A: [Clone](../../clone/trait.clone "trait std::clone::Clone"), Notable traits for [VecDeque](../struct.vecdeque "struct std::collections::VecDeque")<[u8](../../primitive.u8), A> ``` impl<A: Allocator> Read for VecDeque<u8, A> impl<A: Allocator> Write for VecDeque<u8, A> ``` Splits the deque into two at the given index. Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`, and the returned deque contains elements `[at, len)`. Note that the capacity of `self` does not change. Element at index 0 is the front of the queue. ##### Panics Panics if `at > len`. ##### Examples ``` use std::collections::VecDeque; let mut buf: VecDeque<_> = [1, 2, 3].into(); let buf2 = buf.split_off(1); assert_eq!(buf, [1]); assert_eq!(buf2, [2, 3]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2150)1.4.0 · #### pub fn append(&mut self, other: &mut VecDeque<T, A>) Moves all the elements of `other` into `self`, leaving `other` empty. ##### Panics Panics if the new number of elements in self overflows a `usize`. ##### Examples ``` use std::collections::VecDeque; let mut buf: VecDeque<_> = [1, 2].into(); let mut buf2: VecDeque<_> = [3, 4].into(); buf.append(&mut buf2); assert_eq!(buf, [1, 2, 3, 4]); assert_eq!(buf2, []); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2196-2198)1.4.0 · #### pub fn retain<F>(&mut self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), Retains only the elements specified by the predicate. In other words, remove all elements `e` for which `f(&e)` returns false. This method operates in place, visiting each element exactly once in the original order, and preserves the order of the retained elements. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.extend(1..5); buf.retain(|&x| x % 2 == 0); assert_eq!(buf, [2, 4]); ``` Because the elements are visited exactly once in the original order, external state may be used to decide which elements to keep. ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.extend(1..6); let keep = [false, true, true, false, true]; let mut iter = keep.iter(); buf.retain(|_| *iter.next().unwrap()); assert_eq!(buf, [2, 3, 5]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2225-2227)1.61.0 · #### pub fn retain\_mut<F>(&mut self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) T) -> [bool](../../primitive.bool), Retains only the elements specified by the predicate. In other words, remove all elements `e` for which `f(&e)` returns false. This method operates in place, visiting each element exactly once in the original order, and preserves the order of the retained elements. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.extend(1..5); buf.retain_mut(|x| if *x % 2 == 0 { *x += 1; true } else { false }); assert_eq!(buf, [3, 5]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2302)1.33.0 · #### pub fn resize\_with(&mut self, new\_len: usize, generator: impl FnMut() -> T) Modifies the deque in-place so that `len()` is equal to `new_len`, either by removing excess elements from the back or by appending elements generated by calling `generator` to the back. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(5); buf.push_back(10); buf.push_back(15); assert_eq!(buf, [5, 10, 15]); buf.resize_with(5, Default::default); assert_eq!(buf, [5, 10, 15, 0, 0]); buf.resize_with(2, || unreachable!()); assert_eq!(buf, [5, 10]); let mut state = 100; buf.resize_with(5, || { state += 1; state }); assert_eq!(buf, [5, 10, 101, 102, 103]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2368)1.48.0 · #### pub fn make\_contiguous(&mut self) -> &mut [T] Notable traits for &[[u8](../../primitive.u8)] ``` impl Read for &[u8] impl Write for &mut [u8] ``` Rearranges the internal storage of this deque so it is one contiguous slice, which is then returned. This method does not allocate and does not change the order of the inserted elements. As it returns a mutable slice, this can be used to sort a deque. Once the internal storage is contiguous, the [`as_slices`](../struct.vecdeque#method.as_slices) and [`as_mut_slices`](../struct.vecdeque#method.as_mut_slices) methods will return the entire contents of the deque in a single slice. ##### Examples Sorting the content of a deque. ``` use std::collections::VecDeque; let mut buf = VecDeque::with_capacity(15); buf.push_back(2); buf.push_back(1); buf.push_front(3); // sorting the deque buf.make_contiguous().sort(); assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_])); // sorting it in reverse order buf.make_contiguous().sort_by(|a, b| b.cmp(a)); assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_])); ``` Getting immutable access to the contiguous slice. ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(2); buf.push_back(1); buf.push_front(3); buf.make_contiguous(); if let (slice, &[]) = buf.as_slices() { // we can now be sure that `slice` contains all elements of the deque, // while still having immutable access to `buf`. assert_eq!(buf.len(), slice.len()); assert_eq!(slice, &[3, 2, 1] as &[_]); } ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2508)1.36.0 · #### pub fn rotate\_left(&mut self, mid: usize) Rotates the double-ended queue `mid` places to the left. Equivalently, * Rotates item `mid` into the first position. * Pops the first `mid` items and pushes them to the end. * Rotates `len() - mid` places to the right. ##### Panics If `mid` is greater than `len()`. Note that `mid == len()` does *not* panic and is a no-op rotation. ##### Complexity Takes `*O*(min(mid, len() - mid))` time and no extra space. ##### Examples ``` use std::collections::VecDeque; let mut buf: VecDeque<_> = (0..10).collect(); buf.rotate_left(3); assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]); for i in 1..10 { assert_eq!(i * 3 % 10, buf[0]); buf.rotate_left(3); } assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2551)1.36.0 · #### pub fn rotate\_right(&mut self, k: usize) Rotates the double-ended queue `k` places to the right. Equivalently, * Rotates the first item into position `k`. * Pops the last `k` items and pushes them to the front. * Rotates `len() - k` places to the left. ##### Panics If `k` is greater than `len()`. Note that `k == len()` does *not* panic and is a no-op rotation. ##### Complexity Takes `*O*(min(k, len() - k))` time and no extra space. ##### Examples ``` use std::collections::VecDeque; let mut buf: VecDeque<_> = (0..10).collect(); buf.rotate_right(3); assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]); for i in 1..10 { assert_eq!(0, buf[i * 3 % 10]); buf.rotate_right(3); } assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2636-2638)1.54.0 · #### pub fn binary\_search(&self, x: &T) -> Result<usize, usize>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), Binary searches this `VecDeque` for a given element. This behaves similarly to [`contains`](../struct.vecdeque#method.contains) if this `VecDeque` is sorted. If the value is found then [`Result::Ok`](../../result/enum.result#variant.Ok "Result::Ok") is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. If the value is not found then [`Result::Err`](../../result/enum.result#variant.Err "Result::Err") is returned, containing the index where a matching element could be inserted while maintaining sorted order. See also [`binary_search_by`](../struct.vecdeque#method.binary_search_by), [`binary_search_by_key`](../struct.vecdeque#method.binary_search_by_key), and [`partition_point`](../struct.vecdeque#method.partition_point). ##### Examples Looks up a series of four elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in `[1, 4]`. ``` use std::collections::VecDeque; let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into(); assert_eq!(deque.binary_search(&13), Ok(9)); assert_eq!(deque.binary_search(&4), Err(7)); assert_eq!(deque.binary_search(&100), Err(13)); let r = deque.binary_search(&1); assert!(matches!(r, Ok(1..=4))); ``` If you want to insert an item to a sorted deque, while maintaining sort order, consider using [`partition_point`](../struct.vecdeque#method.partition_point): ``` use std::collections::VecDeque; let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into(); let num = 42; let idx = deque.partition_point(|&x| x < num); // The above is equivalent to `let idx = deque.binary_search(&num).unwrap_or_else(|x| x);` deque.insert(idx, num); assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2682-2684)1.54.0 · #### pub fn binary\_search\_by<'a, F>(&'a self, f: F) -> Result<usize, usize>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&'a](../../primitive.reference) T) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Binary searches this `VecDeque` with a comparator function. This behaves similarly to [`contains`](../struct.vecdeque#method.contains) if this `VecDeque` is sorted. The comparator function should implement an order consistent with the sort order of the deque, returning an order code that indicates whether its argument is `Less`, `Equal` or `Greater` than the desired target. If the value is found then [`Result::Ok`](../../result/enum.result#variant.Ok "Result::Ok") is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. If the value is not found then [`Result::Err`](../../result/enum.result#variant.Err "Result::Err") is returned, containing the index where a matching element could be inserted while maintaining sorted order. See also [`binary_search`](../struct.vecdeque#method.binary_search), [`binary_search_by_key`](../struct.vecdeque#method.binary_search_by_key), and [`partition_point`](../struct.vecdeque#method.partition_point). ##### Examples Looks up a series of four elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in `[1, 4]`. ``` use std::collections::VecDeque; let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into(); assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9)); assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7)); assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13)); let r = deque.binary_search_by(|x| x.cmp(&1)); assert!(matches!(r, Ok(1..=4))); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2740-2743)1.54.0 · #### pub fn binary\_search\_by\_key<'a, B, F>( &'a self, b: &B, f: F) -> Result<usize, usize>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&'a](../../primitive.reference) T) -> B, B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), Binary searches this `VecDeque` with a key extraction function. This behaves similarly to [`contains`](../struct.vecdeque#method.contains) if this `VecDeque` is sorted. Assumes that the deque is sorted by the key, for instance with [`make_contiguous().sort_by_key()`](../struct.vecdeque#method.make_contiguous) using the same key extraction function. If the value is found then [`Result::Ok`](../../result/enum.result#variant.Ok "Result::Ok") is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. If the value is not found then [`Result::Err`](../../result/enum.result#variant.Err "Result::Err") is returned, containing the index where a matching element could be inserted while maintaining sorted order. See also [`binary_search`](../struct.vecdeque#method.binary_search), [`binary_search_by`](../struct.vecdeque#method.binary_search_by), and [`partition_point`](../struct.vecdeque#method.partition_point). ##### Examples Looks up a series of four elements in a slice of pairs sorted by their second elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in `[1, 4]`. ``` use std::collections::VecDeque; let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13), (1, 21), (2, 34), (4, 55)].into(); assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9)); assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7)); assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13)); let r = deque.binary_search_by_key(&1, |&(a, b)| b); assert!(matches!(r, Ok(1..=4))); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2792-2794)1.54.0 · #### pub fn partition\_point<P>(&self, pred: P) -> usizewhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), Returns the index of the partition point according to the given predicate (the index of the first element of the second partition). The deque is assumed to be partitioned according to the given predicate. This means that all elements for which the predicate returns true are at the start of the deque and all elements for which the predicate returns false are at the end. For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0 (all odd numbers are at the start, all even at the end). If the deque is not partitioned, the returned result is unspecified and meaningless, as this method performs a kind of binary search. See also [`binary_search`](../struct.vecdeque#method.binary_search), [`binary_search_by`](../struct.vecdeque#method.binary_search_by), and [`binary_search_by_key`](../struct.vecdeque#method.binary_search_by_key). ##### Examples ``` use std::collections::VecDeque; let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].into(); let i = deque.partition_point(|&x| x < 5); assert_eq!(i, 4); assert!(deque.iter().take(i).all(|&x| x < 5)); assert!(deque.iter().skip(i).all(|&x| !(x < 5))); ``` If you want to insert an item to a sorted deque, while maintaining sort order: ``` use std::collections::VecDeque; let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into(); let num = 42; let idx = deque.partition_point(|&x| x < num); deque.insert(idx, num); assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2806)### impl<T, A> VecDeque<T, A>where T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2829)1.16.0 · #### pub fn resize(&mut self, new\_len: usize, value: T) Modifies the deque in-place so that `len()` is equal to new\_len, either by removing excess elements from the back or by appending clones of `value` to the back. ##### Examples ``` use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(5); buf.push_back(10); buf.push_back(15); assert_eq!(buf, [5, 10, 15]); buf.resize(2, 0); assert_eq!(buf, [5, 10]); buf.resize(5, 20); assert_eq!(buf, [5, 10, 20, 20, 20]); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#113)### impl<T, A> Clone for VecDeque<T, A>where T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator") + [Clone](../../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#114)#### fn clone(&self) -> VecDeque<T, A> Notable traits for [VecDeque](../struct.vecdeque "struct std::collections::VecDeque")<[u8](../../primitive.u8), A> ``` impl<A: Allocator> Read for VecDeque<u8, A> impl<A: Allocator> Write for VecDeque<u8, A> ``` Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#120)#### fn clone\_from(&mut self, other: &VecDeque<T, A>) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3023)### impl<T, A> Debug for VecDeque<T, A>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3024)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#162)### impl<T> Default for VecDeque<T, Global> [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#165)#### fn default() -> VecDeque<T, Global> Notable traits for [VecDeque](../struct.vecdeque "struct std::collections::VecDeque")<[u8](../../primitive.u8), A> ``` impl<A: Allocator> Read for VecDeque<u8, A> impl<A: Allocator> Write for VecDeque<u8, A> ``` Creates an empty deque. [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#137)### impl<T, A> Drop for VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#138)#### fn drop(&mut self) Executes the destructor for this type. [Read more](../../ops/trait.drop#tymethod.drop) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3006)1.2.0 · ### impl<'a, T, A> Extend<&'a T> for VecDeque<T, A>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3007)#### fn extend<I>(&mut self, iter: I)where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = [&'a](../../primitive.reference) T>, Extends a collection with the contents of an iterator. [Read more](../../iter/trait.extend#tymethod.extend) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3012)#### fn extend\_one(&mut self, &T) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Extends a collection with exactly one element. [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3017)#### fn extend\_reserve(&mut self, additional: usize) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Reserves capacity in a collection for the given number of additional elements. [Read more](../../iter/trait.extend#method.extend_reserve) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2989)### impl<T, A> Extend<T> for VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2990)#### fn extend<I>(&mut self, iter: I)where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = T>, Extends a collection with the contents of an iterator. [Read more](../../iter/trait.extend#tymethod.extend) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2995)#### fn extend\_one(&mut self, elem: T) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Extends a collection with exactly one element. [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3000)#### fn extend\_reserve(&mut self, additional: usize) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Reserves capacity in a collection for the given number of additional elements. [Read more](../../iter/trait.extend#method.extend_reserve) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3114)1.56.0 · ### impl<T, const N: usize> From<[T; N]> for VecDeque<T, Global> [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3124)#### fn from(arr: [T; N]) -> VecDeque<T, Global> Notable traits for [VecDeque](../struct.vecdeque "struct std::collections::VecDeque")<[u8](../../primitive.u8), A> ``` impl<A: Allocator> Read for VecDeque<u8, A> impl<A: Allocator> Write for VecDeque<u8, A> ``` Converts a `[T; N]` into a `VecDeque<T>`. ``` use std::collections::VecDeque; let deq1 = VecDeque::from([1, 2, 3, 4]); let deq2: VecDeque<_> = [1, 2, 3, 4].into(); assert_eq!(deq1, deq2); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3030)1.10.0 · ### impl<T, A> From<Vec<T, A>> for VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3039)#### fn from(other: Vec<T, A>) -> VecDeque<T, A> Notable traits for [VecDeque](../struct.vecdeque "struct std::collections::VecDeque")<[u8](../../primitive.u8), A> ``` impl<A: Allocator> Read for VecDeque<u8, A> impl<A: Allocator> Write for VecDeque<u8, A> ``` Turn a [`Vec<T>`](../../vec/struct.vec) into a [`VecDeque<T>`](../struct.vecdeque). This avoids reallocating where possible, but the conditions for that are strict, and subject to change, and so shouldn’t be relied upon unless the `Vec<T>` came from `From<VecDeque<T>>` and hasn’t been reallocated. [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3065)1.10.0 · ### impl<T, A> From<VecDeque<T, A>> for Vec<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3095)#### fn from(other: VecDeque<T, A>) -> Vec<T, A> Notable traits for [Vec](../../vec/struct.vec "struct std::vec::Vec")<[u8](../../primitive.u8), A> ``` impl<A: Allocator> Write for Vec<u8, A> ``` Turn a [`VecDeque<T>`](../struct.vecdeque) into a [`Vec<T>`](../../vec/struct.vec). This never needs to re-allocate, but does need to do *O*(*n*) data movement if the circular buffer doesn’t happen to be at the beginning of the allocation. ##### Examples ``` use std::collections::VecDeque; // This one is *O*(1). let deque: VecDeque<_> = (1..5).collect(); let ptr = deque.as_slices().0.as_ptr(); let vec = Vec::from(deque); assert_eq!(vec, [1, 2, 3, 4]); assert_eq!(vec.as_ptr(), ptr); // This one needs data rearranging. let mut deque: VecDeque<_> = (1..5).collect(); deque.push_front(9); deque.push_front(8); let ptr = deque.as_slices().1.as_ptr(); let vec = Vec::from(deque); assert_eq!(vec, [8, 9, 1, 2, 3, 4]); assert_eq!(vec.as_ptr(), ptr); ``` [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2946)### impl<T> FromIterator<T> for VecDeque<T, Global> [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2947)#### fn from\_iter<I>(iter: I) -> VecDeque<T, Global>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = T>, Notable traits for [VecDeque](../struct.vecdeque "struct std::collections::VecDeque")<[u8](../../primitive.u8), A> ``` impl<A: Allocator> Read for VecDeque<u8, A> impl<A: Allocator> Write for VecDeque<u8, A> ``` Creates a value from an iterator. [Read more](../../iter/trait.fromiterator#tymethod.from_iter) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2914)### impl<T, A> Hash for VecDeque<T, A>where T: [Hash](../../hash/trait.hash "trait std::hash::Hash"), A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2915)#### fn hash<H>(&self, state: &mut H)where H: [Hasher](../../hash/trait.hasher "trait std::hash::Hasher"), Feeds this value into the given [`Hasher`](../../hash/trait.hasher "Hasher"). [Read more](../../hash/trait.hash#tymethod.hash) [source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0 · #### fn hash\_slice<H>(data: &[Self], state: &mut H)where H: [Hasher](../../hash/trait.hasher "trait std::hash::Hasher"), Feeds a slice of this type into the given [`Hasher`](../../hash/trait.hasher "Hasher"). [Read more](../../hash/trait.hash#method.hash_slice) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2928)### impl<T, A> Index<usize> for VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), #### type Output = T The returned type after indexing. [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2932)#### fn index(&self, index: usize) -> &T Performs the indexing (`container[index]`) operation. [Read more](../../ops/trait.index#tymethod.index) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2938)### impl<T, A> IndexMut<usize> for VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2940)#### fn index\_mut(&mut self, index: usize) -> &mut T Performs the mutable indexing (`container[index]`) operation. [Read more](../../ops/trait.indexmut#tymethod.index_mut) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2969)### impl<'a, T, A> IntoIterator for &'a VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), #### type Item = &'a T The type of the elements being iterated over. #### type IntoIter = Iter<'a, T> Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2973)#### fn into\_iter(self) -> Iter<'a, T> Notable traits for [Iter](struct.iter "struct std::collections::vec_deque::Iter")<'a, T> ``` impl<'a, T> Iterator for Iter<'a, T> type Item = &'a T; ``` Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2979)### impl<'a, T, A> IntoIterator for &'a mut VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), #### type Item = &'a mut T The type of the elements being iterated over. #### type IntoIter = IterMut<'a, T> Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2983)#### fn into\_iter(self) -> IterMut<'a, T> Notable traits for [IterMut](struct.itermut "struct std::collections::vec_deque::IterMut")<'a, T> ``` impl<'a, T> Iterator for IterMut<'a, T> type Item = &'a mut T; ``` Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2957)### impl<T, A> IntoIterator for VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2963)#### fn into\_iter(self) -> IntoIter<T, A> Notable traits for [IntoIter](struct.intoiter "struct std::collections::vec_deque::IntoIter")<T, A> ``` impl<T, A> Iterator for IntoIter<T, A>where     A: Allocator, type Item = T; ``` Consumes the deque into a front-to-back iterator yielding elements by value. #### type Item = T The type of the elements being iterated over. #### type IntoIter = IntoIter<T, A> Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2906)### impl<T, A> Ord for VecDeque<T, A>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2908)#### fn cmp(&self, other: &VecDeque<T, A>) -> Ordering This method returns an [`Ordering`](../../cmp/enum.ordering "Ordering") between `self` and `other`. [Read more](../../cmp/trait.ord#tymethod.cmp) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#804-807)1.21.0 · #### fn max(self, other: Self) -> Self Compares and returns the maximum of two values. [Read more](../../cmp/trait.ord#method.max) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#831-834)1.21.0 · #### fn min(self, other: Self) -> Self Compares and returns the minimum of two values. [Read more](../../cmp/trait.ord#method.min) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#863-867)1.50.0 · #### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<Self>, Restrict a value to a certain interval. [Read more](../../cmp/trait.ord#method.clamp) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2895)1.17.0 · ### impl<T, U, A, const N: usize> PartialEq<&[U; N]> for VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), T: [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<U>, [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2895)#### fn eq(&self, other: &&[U; N]) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2892)1.17.0 · ### impl<T, U, A> PartialEq<&[U]> for VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), T: [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<U>, [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2892)#### fn eq(&self, other: &&[U]) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2896)1.17.0 · ### impl<T, U, A, const N: usize> PartialEq<&mut [U; N]> for VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), T: [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<U>, [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2896)#### fn eq(&self, other: &&mut [U; N]) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2893)1.17.0 · ### impl<T, U, A> PartialEq<&mut [U]> for VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), T: [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<U>, [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2893)#### fn eq(&self, other: &&mut [U]) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2894)1.17.0 · ### impl<T, U, A, const N: usize> PartialEq<[U; N]> for VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), T: [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<U>, [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2894)#### fn eq(&self, other: &[U; N]) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2891)1.17.0 · ### impl<T, U, A> PartialEq<Vec<U, A>> for VecDeque<T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), T: [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<U>, [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2891)#### fn eq(&self, other: &Vec<U, A>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2850)### impl<T, A> PartialEq<VecDeque<T, A>> for VecDeque<T, A>where T: [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<T>, A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2851)#### fn eq(&self, other: &VecDeque<T, A>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2899)### impl<T, A> PartialOrd<VecDeque<T, A>> for VecDeque<T, A>where T: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<T>, A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2900)#### fn partial\_cmp(&self, other: &VecDeque<T, A>) -> Option<Ordering> This method returns an ordering between `self` and `other` values if one exists. [Read more](../../cmp/trait.partialord#tymethod.partial_cmp) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1138)#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](../../cmp/trait.partialord#method.lt) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1157)#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](../../cmp/trait.partialord#method.le) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1175)#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](../../cmp/trait.partialord#method.gt) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1194)#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](../../cmp/trait.partialord#method.ge) [source](https://doc.rust-lang.org/src/std/io/impls.rs.html#417-437)1.63.0 · ### impl<A: Allocator> Read for VecDeque<u8, A> Read is implemented for `VecDeque<u8>` by consuming bytes from the front of the `VecDeque`. [source](https://doc.rust-lang.org/src/std/io/impls.rs.html#422-427)#### fn read(&mut self, buf: &mut [u8]) -> Result<usize> Fill `buf` with the contents of the “front” slice as returned by [`as_slices`](../struct.vecdeque#method.as_slices "VecDeque::as_slices"). If the contained byte slices of the `VecDeque` are discontiguous, multiple calls to `read` will be needed to read the entire content. [source](https://doc.rust-lang.org/src/std/io/impls.rs.html#430-436)#### fn read\_buf(&mut self, cursor: BorrowedCursor<'\_>) -> Result<()> 🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485)) Pull some bytes from this source into the specified buffer. [Read more](../../io/trait.read#method.read_buf) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#642-644)1.36.0 · #### fn read\_vectored(&mut self, bufs: &mut [IoSliceMut<'\_>]) -> Result<usize> Like `read`, except that it reads into a slice of buffers. [Read more](../../io/trait.read#method.read_vectored) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#655-657)#### fn is\_read\_vectored(&self) -> bool 🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941)) Determines if this `Read`er has an efficient `read_vectored` implementation. [Read more](../../io/trait.read#method.is_read_vectored) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#706-708)#### fn read\_to\_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> Read all bytes until EOF in this source, placing them into `buf`. [Read more](../../io/trait.read#method.read_to_end) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#749-751)#### fn read\_to\_string(&mut self, buf: &mut String) -> Result<usize> Read all bytes until EOF in this source, appending them to `buf`. [Read more](../../io/trait.read#method.read_to_string) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#804-806)1.6.0 · #### fn read\_exact(&mut self, buf: &mut [u8]) -> Result<()> Read the exact number of bytes required to fill `buf`. [Read more](../../io/trait.read#method.read_exact) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#824-839)#### fn read\_buf\_exact(&mut self, cursor: BorrowedCursor<'\_>) -> Result<()> 🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485)) Read the exact number of bytes required to fill `cursor`. [Read more](../../io/trait.read#method.read_buf_exact) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#876-881)#### fn by\_ref(&mut self) -> &mut Selfwhere Self: [Sized](../../marker/trait.sized "trait std::marker::Sized"), Creates a “by reference” adaptor for this instance of `Read`. [Read more](../../io/trait.read#method.by_ref) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#919-924)#### fn bytes(self) -> Bytes<Self>where Self: [Sized](../../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Bytes](../../io/struct.bytes "struct std::io::Bytes")<R> ``` impl<R: Read> Iterator for Bytes<R> type Item = Result<u8>; ``` Transforms this `Read` instance to an [`Iterator`](../../iter/trait.iterator "Iterator") over its bytes. [Read more](../../io/trait.read#method.bytes) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#957-962)#### fn chain<R: Read>(self, next: R) -> Chain<Self, R>where Self: [Sized](../../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Chain](../../io/struct.chain "struct std::io::Chain")<T, U> ``` impl<T: Read, U: Read> Read for Chain<T, U> ``` Creates an adapter which will chain this stream with another. [Read more](../../io/trait.read#method.chain) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#996-1001)#### fn take(self, limit: u64) -> Take<Self>where Self: [Sized](../../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Take](../../io/struct.take "struct std::io::Take")<T> ``` impl<T: Read> Read for Take<T> ``` Creates an adapter which will read at most `limit` bytes from it. [Read more](../../io/trait.read#method.take) [source](https://doc.rust-lang.org/src/std/io/impls.rs.html#441-458)1.63.0 · ### impl<A: Allocator> Write for VecDeque<u8, A> Write is implemented for `VecDeque<u8>` by appending to the `VecDeque`, growing it as needed. [source](https://doc.rust-lang.org/src/std/io/impls.rs.html#443-446)#### fn write(&mut self, buf: &[u8]) -> Result<usize> Write a buffer into this writer, returning how many bytes were written. [Read more](../../io/trait.write#tymethod.write) [source](https://doc.rust-lang.org/src/std/io/impls.rs.html#449-452)#### fn write\_all(&mut self, buf: &[u8]) -> Result<()> Attempts to write an entire buffer into this writer. [Read more](../../io/trait.write#method.write_all) [source](https://doc.rust-lang.org/src/std/io/impls.rs.html#455-457)#### fn flush(&mut self) -> Result<()> Flush this output stream, ensuring that all intermediately buffered contents reach their destination. [Read more](../../io/trait.write#tymethod.flush) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1460-1462)1.36.0 · #### fn write\_vectored(&mut self, bufs: &[IoSlice<'\_>]) -> Result<usize> Like [`write`](../../io/trait.write#tymethod.write), except that it writes from a slice of buffers. [Read more](../../io/trait.write#method.write_vectored) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1475-1477)#### fn is\_write\_vectored(&self) -> bool 🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941)) Determines if this `Write`r has an efficient [`write_vectored`](../../io/trait.write#method.write_vectored) implementation. [Read more](../../io/trait.write#method.is_write_vectored) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1602-1620)#### fn write\_all\_vectored(&mut self, bufs: &mut [IoSlice<'\_>]) -> Result<()> 🔬This is a nightly-only experimental API. (`write_all_vectored` [#70436](https://github.com/rust-lang/rust/issues/70436)) Attempts to write multiple buffers into this writer. [Read more](../../io/trait.write#method.write_all_vectored) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1658-1690)#### fn write\_fmt(&mut self, fmt: Arguments<'\_>) -> Result<()> Writes a formatted string into this writer, returning any error encountered. [Read more](../../io/trait.write#method.write_fmt) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1714-1719)#### fn by\_ref(&mut self) -> &mut Selfwhere Self: [Sized](../../marker/trait.sized "trait std::marker::Sized"), Creates a “by reference” adapter for this instance of `Write`. [Read more](../../io/trait.write#method.by_ref) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2889)### impl<T, A> Eq for VecDeque<T, A>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq"), A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), Auto Trait Implementations -------------------------- ### impl<T, A> RefUnwindSafe for VecDeque<T, A>where A: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<T, A> Send for VecDeque<T, A>where A: [Send](../../marker/trait.send "trait std::marker::Send"), T: [Send](../../marker/trait.send "trait std::marker::Send"), ### impl<T, A> Sync for VecDeque<T, A>where A: [Sync](../../marker/trait.sync "trait std::marker::Sync"), T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<T, A> Unpin for VecDeque<T, A>where A: [Unpin](../../marker/trait.unpin "trait std::marker::Unpin"), T: [Unpin](../../marker/trait.unpin "trait std::marker::Unpin"), ### impl<T, A> UnwindSafe for VecDeque<T, A>where A: [UnwindSafe](../../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), T: [UnwindSafe](../../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::vec_deque::Drain Struct std::collections::vec\_deque::Drain ========================================== ``` pub struct Drain<'a, T, A = Global>where    T: 'a,    A: Allocator,{ /* private fields */ } ``` A draining iterator over the elements of a `VecDeque`. This `struct` is created by the [`drain`](../struct.vecdeque#method.drain) method on [`VecDeque`](../struct.vecdeque "VecDeque"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#47)1.17.0 · ### impl<T, A> Debug for Drain<'\_, T, A>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#48)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#150)### impl<T, A> DoubleEndedIterator for Drain<'\_, T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#152)#### fn next\_back(&mut self) -> Option<T> Removes and returns an element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#65)### impl<T, A> Drop for Drain<'\_, T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#66)#### fn drop(&mut self) Executes the destructor for this type. [Read more](../../ops/trait.drop#tymethod.drop) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#165)### impl<T, A> ExactSizeIterator for Drain<'\_, T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#106)1.0.0 · #### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#138)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#126)### impl<T, A> Iterator for Drain<'\_, T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), #### type Item = T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#130)#### fn next(&mut self) -> Option<T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#143)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../../primitive.reference) T>, P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2920-2923)1.0.0 · #### fn rposition<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Self: [ExactSizeIterator](../../iter/trait.exactsizeiterator "trait std::iter::ExactSizeIterator") + [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Searches for an element in an iterator from the right, returning its index. [Read more](../../iter/trait.iterator#method.rposition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)#### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)#### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)1.0.0 · #### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#168)1.26.0 · ### impl<T, A> FusedIterator for Drain<'\_, T, A>where A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#62)### impl<T, A> Send for Drain<'\_, T, A>where T: [Send](../../marker/trait.send "trait std::marker::Send"), A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator") + [Send](../../marker/trait.send "trait std::marker::Send"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#60)### impl<T, A> Sync for Drain<'\_, T, A>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), A: [Allocator](../../alloc/trait.allocator "trait std::alloc::Allocator") + [Sync](../../marker/trait.sync "trait std::marker::Sync"), Auto Trait Implementations -------------------------- ### impl<'a, T, A> RefUnwindSafe for Drain<'a, T, A>where A: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T, A> Unpin for Drain<'a, T, A> ### impl<'a, T, A> UnwindSafe for Drain<'a, T, A>where A: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::vec_deque::Iter Struct std::collections::vec\_deque::Iter ========================================= ``` pub struct Iter<'a, T>where    T: 'a,{ /* private fields */ } ``` An iterator over the elements of a `VecDeque`. This `struct` is created by the [`iter`](../struct.vecdeque#method.iter) method on [`super::VecDeque`](../struct.vecdeque "super::VecDeque"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#45)### impl<T> Clone for Iter<'\_, T> [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#46)#### fn clone(&self) -> Iter<'\_, T> Notable traits for [Iter](struct.iter "struct std::collections::vec_deque::Iter")<'a, T> ``` impl<'a, T> Iterator for Iter<'a, T> type Item = &'a T; ``` Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#28)1.17.0 · ### impl<T> Debug for Iter<'\_, T>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#29)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#142)### impl<'a, T> DoubleEndedIterator for Iter<'a, T> [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#144)#### fn next\_back(&mut self) -> Option<&'a T> Removes and returns an element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#155-157)#### fn rfold<Acc, F>(self, accum: Acc, f: F) -> Accwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Acc, <[Iter](struct.iter "struct std::collections::vec_deque::Iter")<'a, T> as [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Acc, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#169-173)#### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, <[Iter](struct.iter "struct std::collections::vec_deque::Iter")<'a, T> as [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, [Iter](struct.iter "struct std::collections::vec_deque::Iter")<'a, T>: [Sized](../../marker/trait.sized "trait std::marker::Sized"), This is the reverse version of [`Iterator::try_fold()`](../../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#199)### impl<T> ExactSizeIterator for Iter<'\_, T> [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#200)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#106)#### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#52)### impl<'a, T> Iterator for Iter<'a, T> #### type Item = &'a T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#56)#### fn next(&mut self) -> Option<&'a T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#69)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#74-76)#### fn fold<Acc, F>(self, accum: Acc, f: F) -> Accwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Acc, <[Iter](struct.iter "struct std::collections::vec_deque::Iter")<'a, T> as [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Acc, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#88-92)#### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, <[Iter](struct.iter "struct std::collections::vec_deque::Iter")<'a, T> as [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, [Iter](struct.iter "struct std::collections::vec_deque::Iter")<'a, T>: [Sized](../../marker/trait.sized "trait std::marker::Sized"), An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#115)#### fn nth(&mut self, n: usize) -> Option<<Iter<'a, T> as Iterator>::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#126)#### fn last(self) -> Option<&'a T> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../../primitive.reference) T>, P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2920-2923)#### fn rposition<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Self: [ExactSizeIterator](../../iter/trait.exactsizeiterator "trait std::iter::ExactSizeIterator") + [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Searches for an element in an iterator from the right, returning its index. [Read more](../../iter/trait.iterator#method.rposition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)#### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)#### fn cycle(self) -> Cycle<Self>where Self: [Clone](../../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#206)1.26.0 · ### impl<T> FusedIterator for Iter<'\_, T> [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#209)### impl<T> TrustedLen for Iter<'\_, T> Auto Trait Implementations -------------------------- ### impl<'a, T> RefUnwindSafe for Iter<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T> Send for Iter<'a, T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T> Sync for Iter<'a, T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T> Unpin for Iter<'a, T> ### impl<'a, T> UnwindSafe for Iter<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Module std::collections::linked_list Module std::collections::linked\_list ===================================== A doubly-linked list with owned nodes. The `LinkedList` allows pushing and popping elements at either end in constant time. NOTE: It is almost always better to use [`Vec`](../../vec/struct.vec) or [`VecDeque`](../struct.vecdeque) because array-based containers are generally faster, more memory efficient, and make better use of CPU cache. Structs ------- [Cursor](struct.cursor "std::collections::linked_list::Cursor struct")Experimental A cursor over a `LinkedList`. [CursorMut](struct.cursormut "std::collections::linked_list::CursorMut struct")Experimental A cursor over a `LinkedList` with editing operations. [DrainFilter](struct.drainfilter "std::collections::linked_list::DrainFilter struct")Experimental An iterator produced by calling `drain_filter` on LinkedList. [IntoIter](struct.intoiter "std::collections::linked_list::IntoIter struct") An owning iterator over the elements of a `LinkedList`. [Iter](struct.iter "std::collections::linked_list::Iter struct") An iterator over the elements of a `LinkedList`. [IterMut](struct.itermut "std::collections::linked_list::IterMut struct") A mutable iterator over the elements of a `LinkedList`. [LinkedList](struct.linkedlist "std::collections::linked_list::LinkedList struct") A doubly-linked list with owned nodes. rust Struct std::collections::linked_list::CursorMut Struct std::collections::linked\_list::CursorMut ================================================ ``` pub struct CursorMut<'a, T>where    T: 'a,{ /* private fields */ } ``` 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) A cursor over a `LinkedList` with editing operations. A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can safely mutate the list during iteration. This is because the lifetime of its yielded references is tied to its own lifetime, instead of just the underlying list. This means cursors cannot yield multiple elements at once. Cursors always rest between two elements in the list, and index in a logically circular way. To accommodate this, there is a “ghost” non-element that yields `None` between the head and tail of the list. Implementations --------------- [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1304)### impl<'a, T> CursorMut<'a, T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1311)#### pub fn index(&self) -> Option<usize> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Returns the cursor position index within the `LinkedList`. This returns `None` if the cursor is currently pointing to the “ghost” non-element. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1322)#### pub fn move\_next(&mut self) 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Moves the cursor to the next element of the `LinkedList`. If the cursor is pointing to the “ghost” non-element then this will move it to the first element of the `LinkedList`. If it is pointing to the last element of the `LinkedList` then this will move it to the “ghost” non-element. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1344)#### pub fn move\_prev(&mut self) 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Moves the cursor to the previous element of the `LinkedList`. If the cursor is pointing to the “ghost” non-element then this will move it to the last element of the `LinkedList`. If it is pointing to the first element of the `LinkedList` then this will move it to the “ghost” non-element. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1366)#### pub fn current(&mut self) -> Option<&mut T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Returns a reference to the element that the cursor is currently pointing to. This returns `None` if the cursor is currently pointing to the “ghost” non-element. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1376)#### pub fn peek\_next(&mut self) -> Option<&mut T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Returns a reference to the next element. If the cursor is pointing to the “ghost” non-element then this returns the first element of the `LinkedList`. If it is pointing to the last element of the `LinkedList` then this returns `None`. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1392)#### pub fn peek\_prev(&mut self) -> Option<&mut T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Returns a reference to the previous element. If the cursor is pointing to the “ghost” non-element then this returns the last element of the `LinkedList`. If it is pointing to the first element of the `LinkedList` then this returns `None`. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1409)#### pub fn as\_cursor(&self) -> Cursor<'\_, T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Returns a read-only cursor pointing to the current element. The lifetime of the returned `Cursor` is bound to that of the `CursorMut`, which means it cannot outlive the `CursorMut` and that the `CursorMut` is frozen for the lifetime of the `Cursor`. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1416)### impl<'a, T> CursorMut<'a, T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1422)#### pub fn insert\_after(&mut self, item: T) 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Inserts a new element into the `LinkedList` after the current one. If the cursor is pointing at the “ghost” non-element then the new element is inserted at the front of the `LinkedList`. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1442)#### pub fn insert\_before(&mut self, item: T) 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Inserts a new element into the `LinkedList` before the current one. If the cursor is pointing at the “ghost” non-element then the new element is inserted at the end of the `LinkedList`. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1462)#### pub fn remove\_current(&mut self) -> Option<T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Removes the current element from the `LinkedList`. The element that was removed is returned, and the cursor is moved to point to the next element in the `LinkedList`. If the cursor is currently pointing to the “ghost” non-element then no element is removed and `None` is returned. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1480)#### pub fn remove\_current\_as\_list(&mut self) -> Option<LinkedList<T>> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Removes the current element from the `LinkedList` without deallocating the list node. The node that was removed is returned as a new `LinkedList` containing only this node. The cursor is moved to point to the next element in the current `LinkedList`. If the cursor is currently pointing to the “ghost” non-element then no element is removed and `None` is returned. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1502)#### pub fn splice\_after(&mut self, list: LinkedList<T>) 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Inserts the elements from the given `LinkedList` after the current one. If the cursor is pointing at the “ghost” non-element then the new elements are inserted at the start of the `LinkedList`. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1525)#### pub fn splice\_before(&mut self, list: LinkedList<T>) 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Inserts the elements from the given `LinkedList` before the current one. If the cursor is pointing at the “ghost” non-element then the new elements are inserted at the end of the `LinkedList`. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1547)#### pub fn split\_after(&mut self) -> LinkedList<T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Splits the list into two after the current element. This will return a new list consisting of everything after the cursor, with the original list retaining everything before. If the cursor is pointing at the “ghost” non-element then the entire contents of the `LinkedList` are moved. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1563)#### pub fn split\_before(&mut self) -> LinkedList<T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Splits the list into two before the current element. This will return a new list consisting of everything before the cursor, with the original list retaining everything after. If the cursor is pointing at the “ghost” non-element then the entire contents of the `LinkedList` are moved. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1576)#### pub fn push\_front(&mut self, elt: T) 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Appends an element to the front of the cursor’s parent list. The node that the cursor points to is unchanged, even if it is the “ghost” node. This operation should compute in *O*(1) time. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1589)#### pub fn push\_back(&mut self, elt: T) 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Appends an element to the back of the cursor’s parent list. The node that the cursor points to is unchanged, even if it is the “ghost” node. This operation should compute in *O*(1) time. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1608)#### pub fn pop\_front(&mut self) -> Option<T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Removes the first element from the cursor’s parent list and returns it, or None if the list is empty. The element the cursor points to remains unchanged, unless it was pointing to the front element. In that case, it points to the new front element. This operation should compute in *O*(1) time. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1635)#### pub fn pop\_back(&mut self) -> Option<T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Removes the last element from the cursor’s parent list and returns it, or None if the list is empty. The element the cursor points to remains unchanged, unless it was pointing to the back element. In that case, it points to the “ghost” element. This operation should compute in *O*(1) time. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1655)#### pub fn front(&self) -> Option<&T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Provides a reference to the front element of the cursor’s parent list, or None if the list is empty. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1663)#### pub fn front\_mut(&mut self) -> Option<&mut T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Provides a mutable reference to the front element of the cursor’s parent list, or None if the list is empty. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1671)#### pub fn back(&self) -> Option<&T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Provides a reference to the back element of the cursor’s parent list, or None if the list is empty. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1698)#### pub fn back\_mut(&mut self) -> Option<&mut T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Provides a mutable reference to back element of the cursor’s parent list, or `None` if the list is empty. ##### Examples Building and mutating a list with a cursor, then getting the back element: ``` #![feature(linked_list_cursors)] use std::collections::LinkedList; let mut dl = LinkedList::new(); dl.push_front(3); dl.push_front(2); dl.push_front(1); let mut cursor = dl.cursor_front_mut(); *cursor.current().unwrap() = 99; *cursor.back_mut().unwrap() = 0; let mut contents = dl.into_iter(); assert_eq!(contents.next(), Some(99)); assert_eq!(contents.next(), Some(2)); assert_eq!(contents.next(), Some(0)); assert_eq!(contents.next(), None); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1181)### impl<T> Debug for CursorMut<'\_, T>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1182)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#2009)### impl<T> Send for CursorMut<'\_, T>where T: [Send](../../marker/trait.send "trait std::marker::Send"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#2012)### impl<T> Sync for CursorMut<'\_, T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), Auto Trait Implementations -------------------------- ### impl<'a, T> RefUnwindSafe for CursorMut<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T> Unpin for CursorMut<'a, T> ### impl<'a, T> !UnwindSafe for CursorMut<'a, T> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Struct std::collections::linked_list::IterMut Struct std::collections::linked\_list::IterMut ============================================== ``` pub struct IterMut<'a, T>where    T: 'a,{ /* private fields */ } ``` A mutable iterator over the elements of a `LinkedList`. This `struct` is created by [`LinkedList::iter_mut()`](../struct.linkedlist#method.iter_mut "LinkedList::iter_mut()"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#113)1.17.0 · ### impl<T> Debug for IterMut<'\_, T>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#114)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1109)### impl<'a, T> DoubleEndedIterator for IterMut<'a, T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1111)#### fn next\_back(&mut self) -> Option<&'a mut T> Removes and returns an element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1127)### impl<T> ExactSizeIterator for IterMut<'\_, T> [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#106)#### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#138)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1079)### impl<'a, T> Iterator for IterMut<'a, T> #### type Item = &'a mut T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1083)#### fn next(&mut self) -> Option<&'a mut T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1098)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1103)#### fn last(self) -> Option<&'a mut T> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../../primitive.reference) T>, P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2920-2923)#### fn rposition<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Self: [ExactSizeIterator](../../iter/trait.exactsizeiterator "trait std::iter::ExactSizeIterator") + [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Searches for an element in an iterator from the right, returning its index. [Read more](../../iter/trait.iterator#method.rposition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)#### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1130)1.26.0 · ### impl<T> FusedIterator for IterMut<'\_, T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1997)### impl<T> Send for IterMut<'\_, T>where T: [Send](../../marker/trait.send "trait std::marker::Send"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#2000)### impl<T> Sync for IterMut<'\_, T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), Auto Trait Implementations -------------------------- ### impl<'a, T> RefUnwindSafe for IterMut<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T> Unpin for IterMut<'a, T> ### impl<'a, T> !UnwindSafe for IterMut<'a, T> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::linked_list::IntoIter Struct std::collections::linked\_list::IntoIter =============================================== ``` pub struct IntoIter<T> { /* private fields */ } ``` An owning iterator over the elements of a `LinkedList`. This `struct` is created by the [`into_iter`](../struct.linkedlist#method.into_iter) method on [`LinkedList`](../struct.linkedlist "LinkedList") (provided by the [`IntoIterator`](../../iter/trait.intoiterator) trait). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#134)### impl<T> Clone for IntoIter<T>where T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#134)#### fn clone(&self) -> IntoIter<T> Notable traits for [IntoIter](struct.intoiter "struct std::collections::linked_list::IntoIter")<T> ``` impl<T> Iterator for IntoIter<T> type Item = T; ``` Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#141)1.17.0 · ### impl<T> Debug for IntoIter<T>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#142)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1798)### impl<T> DoubleEndedIterator for IntoIter<T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1800)#### fn next\_back(&mut self) -> Option<T> Removes and returns an element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1806)### impl<T> ExactSizeIterator for IntoIter<T> [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#106)#### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#138)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1783)### impl<T> Iterator for IntoIter<T> #### type Item = T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1787)#### fn next(&mut self) -> Option<T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1792)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../../primitive.reference) T>, P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2920-2923)#### fn rposition<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Self: [ExactSizeIterator](../../iter/trait.exactsizeiterator "trait std::iter::ExactSizeIterator") + [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Searches for an element in an iterator from the right, returning its index. [Read more](../../iter/trait.iterator#method.rposition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)#### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1809)1.26.0 · ### impl<T> FusedIterator for IntoIter<T> Auto Trait Implementations -------------------------- ### impl<T> RefUnwindSafe for IntoIter<T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<T> Send for IntoIter<T>where T: [Send](../../marker/trait.send "trait std::marker::Send"), ### impl<T> Sync for IntoIter<T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<T> Unpin for IntoIter<T> ### impl<T> UnwindSafe for IntoIter<T>where T: [UnwindSafe](../../panic/trait.unwindsafe "trait std::panic::UnwindSafe") + [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::linked_list::DrainFilter Struct std::collections::linked\_list::DrainFilter ================================================== ``` pub struct DrainFilter<'a, T, F>where    T: 'a,    F: 'a + FnMut(&mut T) -> bool,{ /* private fields */ } ``` 🔬This is a nightly-only experimental API. (`drain_filter` [#43244](https://github.com/rust-lang/rust/issues/43244)) An iterator produced by calling `drain_filter` on LinkedList. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1773)### impl<T, F> Debug for DrainFilter<'\_, T, F>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) T) -> [bool](../../primitive.bool), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1777)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1746)### impl<T, F> Drop for DrainFilter<'\_, T, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) T) -> [bool](../../primitive.bool), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1750)#### fn drop(&mut self) Executes the destructor for this type. [Read more](../../ops/trait.drop#tymethod.drop) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1717)### impl<T, F> Iterator for DrainFilter<'\_, T, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) T) -> [bool](../../primitive.bool), #### type Item = T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1723)#### fn next(&mut self) -> Option<T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1740)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) Auto Trait Implementations -------------------------- ### impl<'a, T, F> RefUnwindSafe for DrainFilter<'a, T, F>where F: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T, F> !Send for DrainFilter<'a, T, F> ### impl<'a, T, F> !Sync for DrainFilter<'a, T, F> ### impl<'a, T, F> Unpin for DrainFilter<'a, T, F>where F: [Unpin](../../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, T, F> !UnwindSafe for DrainFilter<'a, T, F> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::linked_list::LinkedList Struct std::collections::linked\_list::LinkedList ================================================= ``` pub struct LinkedList<T> { /* private fields */ } ``` A doubly-linked list with owned nodes. The `LinkedList` allows pushing and popping elements at either end in constant time. A `LinkedList` with a known list of items can be initialized from an array: ``` use std::collections::LinkedList; let list = LinkedList::from([1, 2, 3]); ``` NOTE: It is almost always better to use [`Vec`](../../vec/struct.vec) or [`VecDeque`](../struct.vecdeque) because array-based containers are generally faster, more memory efficient, and make better use of CPU cache. Implementations --------------- [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#409)### impl<T> LinkedList<T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#423)const: 1.39.0 · #### pub const fn new() -> LinkedList<T> Creates an empty `LinkedList`. ##### Examples ``` use std::collections::LinkedList; let list: LinkedList<u32> = LinkedList::new(); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#457)#### pub fn append(&mut self, other: &mut LinkedList<T>) Moves all elements from `other` to the end of the list. This reuses all the nodes from `other` and moves them into `self`. After this operation, `other` becomes empty. This operation should compute in *O*(1) time and *O*(1) memory. ##### Examples ``` use std::collections::LinkedList; let mut list1 = LinkedList::new(); list1.push_back('a'); let mut list2 = LinkedList::new(); list2.push_back('b'); list2.push_back('c'); list1.append(&mut list2); let mut iter = list1.iter(); assert_eq!(iter.next(), Some(&'a')); assert_eq!(iter.next(), Some(&'b')); assert_eq!(iter.next(), Some(&'c')); assert!(iter.next().is_none()); assert!(list2.is_empty()); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#497)#### pub fn iter(&self) -> Iter<'\_, T> Notable traits for [Iter](struct.iter "struct std::collections::linked_list::Iter")<'a, T> ``` impl<'a, T> Iterator for Iter<'a, T> type Item = &'a T; ``` Provides a forward iterator. ##### Examples ``` use std::collections::LinkedList; let mut list: LinkedList<u32> = LinkedList::new(); list.push_back(0); list.push_back(1); list.push_back(2); let mut iter = list.iter(); assert_eq!(iter.next(), Some(&0)); assert_eq!(iter.next(), Some(&1)); assert_eq!(iter.next(), Some(&2)); assert_eq!(iter.next(), None); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#526)#### pub fn iter\_mut(&mut self) -> IterMut<'\_, T> Notable traits for [IterMut](struct.itermut "struct std::collections::linked_list::IterMut")<'a, T> ``` impl<'a, T> Iterator for IterMut<'a, T> type Item = &'a mut T; ``` Provides a forward iterator with mutable references. ##### Examples ``` use std::collections::LinkedList; let mut list: LinkedList<u32> = LinkedList::new(); list.push_back(0); list.push_back(1); list.push_back(2); for element in list.iter_mut() { *element += 10; } let mut iter = list.iter(); assert_eq!(iter.next(), Some(&10)); assert_eq!(iter.next(), Some(&11)); assert_eq!(iter.next(), Some(&12)); assert_eq!(iter.next(), None); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#536)#### pub fn cursor\_front(&self) -> Cursor<'\_, T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Provides a cursor at the front element. The cursor is pointing to the “ghost” non-element if the list is empty. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#546)#### pub fn cursor\_front\_mut(&mut self) -> CursorMut<'\_, T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Provides a cursor with editing operations at the front element. The cursor is pointing to the “ghost” non-element if the list is empty. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#556)#### pub fn cursor\_back(&self) -> Cursor<'\_, T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Provides a cursor at the back element. The cursor is pointing to the “ghost” non-element if the list is empty. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#566)#### pub fn cursor\_back\_mut(&mut self) -> CursorMut<'\_, T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Provides a cursor with editing operations at the back element. The cursor is pointing to the “ghost” non-element if the list is empty. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#588)#### pub fn is\_empty(&self) -> bool Returns `true` if the `LinkedList` is empty. This operation should compute in *O*(1) time. ##### Examples ``` use std::collections::LinkedList; let mut dl = LinkedList::new(); assert!(dl.is_empty()); dl.push_front("foo"); assert!(!dl.is_empty()); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#615)#### pub fn len(&self) -> usize Returns the length of the `LinkedList`. This operation should compute in *O*(1) time. ##### Examples ``` use std::collections::LinkedList; let mut dl = LinkedList::new(); dl.push_front(2); assert_eq!(dl.len(), 1); dl.push_front(1); assert_eq!(dl.len(), 2); dl.push_back(3); assert_eq!(dl.len(), 3); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#641)#### pub fn clear(&mut self) Removes all elements from the `LinkedList`. This operation should compute in *O*(*n*) time. ##### Examples ``` use std::collections::LinkedList; let mut dl = LinkedList::new(); dl.push_front(2); dl.push_front(1); assert_eq!(dl.len(), 2); assert_eq!(dl.front(), Some(&1)); dl.clear(); assert_eq!(dl.len(), 0); assert_eq!(dl.front(), None); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#665-667)1.12.0 · #### pub fn contains(&self, x: &T) -> boolwhere T: [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<T>, Returns `true` if the `LinkedList` contains an element equal to the given value. This operation should compute linearly in *O*(*n*) time. ##### Examples ``` use std::collections::LinkedList; let mut list: LinkedList<u32> = LinkedList::new(); list.push_back(0); list.push_back(1); list.push_back(2); assert_eq!(list.contains(&0), true); assert_eq!(list.contains(&10), false); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#691)#### pub fn front(&self) -> Option<&T> Provides a reference to the front element, or `None` if the list is empty. This operation should compute in *O*(1) time. ##### Examples ``` use std::collections::LinkedList; let mut dl = LinkedList::new(); assert_eq!(dl.front(), None); dl.push_front(1); assert_eq!(dl.front(), Some(&1)); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#720)#### pub fn front\_mut(&mut self) -> Option<&mut T> Provides a mutable reference to the front element, or `None` if the list is empty. This operation should compute in *O*(1) time. ##### Examples ``` use std::collections::LinkedList; let mut dl = LinkedList::new(); assert_eq!(dl.front(), None); dl.push_front(1); assert_eq!(dl.front(), Some(&1)); match dl.front_mut() { None => {}, Some(x) => *x = 5, } assert_eq!(dl.front(), Some(&5)); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#743)#### pub fn back(&self) -> Option<&T> Provides a reference to the back element, or `None` if the list is empty. This operation should compute in *O*(1) time. ##### Examples ``` use std::collections::LinkedList; let mut dl = LinkedList::new(); assert_eq!(dl.back(), None); dl.push_back(1); assert_eq!(dl.back(), Some(&1)); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#771)#### pub fn back\_mut(&mut self) -> Option<&mut T> Provides a mutable reference to the back element, or `None` if the list is empty. This operation should compute in *O*(1) time. ##### Examples ``` use std::collections::LinkedList; let mut dl = LinkedList::new(); assert_eq!(dl.back(), None); dl.push_back(1); assert_eq!(dl.back(), Some(&1)); match dl.back_mut() { None => {}, Some(x) => *x = 5, } assert_eq!(dl.back(), Some(&5)); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#793)#### pub fn push\_front(&mut self, elt: T) Adds an element first in the list. This operation should compute in *O*(1) time. ##### Examples ``` use std::collections::LinkedList; let mut dl = LinkedList::new(); dl.push_front(2); assert_eq!(dl.front().unwrap(), &2); dl.push_front(1); assert_eq!(dl.front().unwrap(), &1); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#817)#### pub fn pop\_front(&mut self) -> Option<T> Removes the first element and returns it, or `None` if the list is empty. This operation should compute in *O*(1) time. ##### Examples ``` use std::collections::LinkedList; let mut d = LinkedList::new(); assert_eq!(d.pop_front(), None); d.push_front(1); d.push_front(3); assert_eq!(d.pop_front(), Some(3)); assert_eq!(d.pop_front(), Some(1)); assert_eq!(d.pop_front(), None); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#836)#### pub fn push\_back(&mut self, elt: T) Appends an element to the back of a list. This operation should compute in *O*(1) time. ##### Examples ``` use std::collections::LinkedList; let mut d = LinkedList::new(); d.push_back(1); d.push_back(3); assert_eq!(3, *d.back().unwrap()); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#857)#### pub fn pop\_back(&mut self) -> Option<T> Removes the last element from a list and returns it, or `None` if it is empty. This operation should compute in *O*(1) time. ##### Examples ``` use std::collections::LinkedList; let mut d = LinkedList::new(); assert_eq!(d.pop_back(), None); d.push_back(1); d.push_back(3); assert_eq!(d.pop_back(), Some(3)); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#887)#### pub fn split\_off(&mut self, at: usize) -> LinkedList<T> Splits the list into two at the given index. Returns everything after the given index, including the index. This operation should compute in *O*(*n*) time. ##### Panics Panics if `at > len`. ##### Examples ``` use std::collections::LinkedList; let mut d = LinkedList::new(); d.push_front(1); d.push_front(2); d.push_front(3); let mut split = d.split_off(2); assert_eq!(split.pop_front(), Some(1)); assert_eq!(split.pop_front(), None); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#942)#### pub fn remove(&mut self, at: usize) -> T 🔬This is a nightly-only experimental API. (`linked_list_remove` [#69210](https://github.com/rust-lang/rust/issues/69210)) Removes the element at the given index and returns it. This operation should compute in *O*(*n*) time. ##### Panics Panics if at >= len ##### Examples ``` #![feature(linked_list_remove)] use std::collections::LinkedList; let mut d = LinkedList::new(); d.push_front(1); d.push_front(2); d.push_front(3); assert_eq!(d.remove(1), 2); assert_eq!(d.remove(0), 3); assert_eq!(d.remove(0), 1); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#991-993)#### pub fn drain\_filter<F>(&mut self, filter: F) -> DrainFilter<'\_, T, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) T) -> [bool](../../primitive.bool), Notable traits for [DrainFilter](struct.drainfilter "struct std::collections::linked_list::DrainFilter")<'\_, T, F> ``` impl<T, F> Iterator for DrainFilter<'_, T, F>where     F: FnMut(&mut T) -> bool, type Item = T; ``` 🔬This is a nightly-only experimental API. (`drain_filter` [#43244](https://github.com/rust-lang/rust/issues/43244)) Creates an iterator which uses a closure to determine if an element should be removed. If the closure returns true, then the element is removed and yielded. If the closure returns false, the element will remain in the list and will not be yielded by the iterator. Note that `drain_filter` lets you mutate every element in the filter closure, regardless of whether you choose to keep or remove it. ##### Examples Splitting a list into evens and odds, reusing the original list: ``` #![feature(drain_filter)] use std::collections::LinkedList; let mut numbers: LinkedList<u32> = LinkedList::new(); numbers.extend(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]); let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<LinkedList<_>>(); let odds = numbers; assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![2, 4, 6, 8, 14]); assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 9, 11, 13, 15]); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1918)### impl<T> Clone for LinkedList<T>where T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1919)#### fn clone(&self) -> LinkedList<T> Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1923)#### fn clone\_from(&mut self, other: &LinkedList<T>) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1938)### impl<T> Debug for LinkedList<T>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1939)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#401)### impl<T> Default for LinkedList<T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#404)#### fn default() -> LinkedList<T> Creates an empty `LinkedList<T>`. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1004)### impl<T> Drop for LinkedList<T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1005)#### fn drop(&mut self) Executes the destructor for this type. [Read more](../../ops/trait.drop#tymethod.drop) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1877)1.2.0 · ### impl<'a, T> Extend<&'a T> for LinkedList<T>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1878)#### fn extend<I>(&mut self, iter: I)where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = [&'a](../../primitive.reference) T>, Extends a collection with the contents of an iterator. [Read more](../../iter/trait.extend#tymethod.extend) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1883)#### fn extend\_one(&mut self, &'a T) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Extends a collection with exactly one element. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#379)#### fn extend\_reserve(&mut self, additional: usize) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Reserves capacity in a collection for the given number of additional elements. [Read more](../../iter/trait.extend#method.extend_reserve) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1853)### impl<T> Extend<T> for LinkedList<T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1854)#### fn extend<I>(&mut self, iter: I)where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = T>, Extends a collection with the contents of an iterator. [Read more](../../iter/trait.extend#tymethod.extend) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1859)#### fn extend\_one(&mut self, elem: T) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Extends a collection with exactly one element. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#379)#### fn extend\_reserve(&mut self, additional: usize) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Reserves capacity in a collection for the given number of additional elements. [Read more](../../iter/trait.extend#method.extend_reserve) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1955)1.56.0 · ### impl<T, const N: usize> From<[T; N]> for LinkedList<T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1965)#### fn from(arr: [T; N]) -> LinkedList<T> Converts a `[T; N]` into a `LinkedList<T>`. ``` use std::collections::LinkedList; let list1 = LinkedList::from([1, 2, 3, 4]); let list2: LinkedList<_> = [1, 2, 3, 4].into(); assert_eq!(list1, list2); ``` [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1812)### impl<T> FromIterator<T> for LinkedList<T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1813)#### fn from\_iter<I>(iter: I) -> LinkedList<T>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = T>, Creates a value from an iterator. [Read more](../../iter/trait.fromiterator#tymethod.from_iter) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1945)### impl<T> Hash for LinkedList<T>where T: [Hash](../../hash/trait.hash "trait std::hash::Hash"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1946)#### fn hash<H>(&self, state: &mut H)where H: [Hasher](../../hash/trait.hasher "trait std::hash::Hasher"), Feeds this value into the given [`Hasher`](../../hash/trait.hasher "Hasher"). [Read more](../../hash/trait.hash#tymethod.hash) [source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0 · #### fn hash\_slice<H>(data: &[Self], state: &mut H)where H: [Hasher](../../hash/trait.hasher "trait std::hash::Hasher"), Feeds a slice of this type into the given [`Hasher`](../../hash/trait.hasher "Hasher"). [Read more](../../hash/trait.hash#method.hash_slice) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1833)### impl<'a, T> IntoIterator for &'a LinkedList<T> #### type Item = &'a T The type of the elements being iterated over. #### type IntoIter = Iter<'a, T> Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1837)#### fn into\_iter(self) -> Iter<'a, T> Notable traits for [Iter](struct.iter "struct std::collections::linked_list::Iter")<'a, T> ``` impl<'a, T> Iterator for Iter<'a, T> type Item = &'a T; ``` Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1843)### impl<'a, T> IntoIterator for &'a mut LinkedList<T> #### type Item = &'a mut T The type of the elements being iterated over. #### type IntoIter = IterMut<'a, T> Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1847)#### fn into\_iter(self) -> IterMut<'a, T> Notable traits for [IterMut](struct.itermut "struct std::collections::linked_list::IterMut")<'a, T> ``` impl<'a, T> Iterator for IterMut<'a, T> type Item = &'a mut T; ``` Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1821)### impl<T> IntoIterator for LinkedList<T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1827)#### fn into\_iter(self) -> IntoIter<T> Notable traits for [IntoIter](struct.intoiter "struct std::collections::linked_list::IntoIter")<T> ``` impl<T> Iterator for IntoIter<T> type Item = T; ``` Consumes the list into an iterator yielding elements by value. #### type Item = T The type of the elements being iterated over. #### type IntoIter = IntoIter<T> Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1910)### impl<T> Ord for LinkedList<T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1912)#### fn cmp(&self, other: &LinkedList<T>) -> Ordering This method returns an [`Ordering`](../../cmp/enum.ordering "Ordering") between `self` and `other`. [Read more](../../cmp/trait.ord#tymethod.cmp) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#804-807)1.21.0 · #### fn max(self, other: Self) -> Self Compares and returns the maximum of two values. [Read more](../../cmp/trait.ord#method.max) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#831-834)1.21.0 · #### fn min(self, other: Self) -> Self Compares and returns the minimum of two values. [Read more](../../cmp/trait.ord#method.min) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#863-867)1.50.0 · #### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<Self>, Restrict a value to a certain interval. [Read more](../../cmp/trait.ord#method.clamp) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1889)### impl<T> PartialEq<LinkedList<T>> for LinkedList<T>where T: [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<T>, [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1890)#### fn eq(&self, other: &LinkedList<T>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1894)#### fn ne(&self, other: &LinkedList<T>) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1903)### impl<T> PartialOrd<LinkedList<T>> for LinkedList<T>where T: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<T>, [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1904)#### fn partial\_cmp(&self, other: &LinkedList<T>) -> Option<Ordering> This method returns an ordering between `self` and `other` values if one exists. [Read more](../../cmp/trait.partialord#tymethod.partial_cmp) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1138)#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](../../cmp/trait.partialord#method.lt) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1157)#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](../../cmp/trait.partialord#method.le) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1175)#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](../../cmp/trait.partialord#method.gt) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1194)#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](../../cmp/trait.partialord#method.ge) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1900)### impl<T> Eq for LinkedList<T>where T: [Eq](../../cmp/trait.eq "trait std::cmp::Eq"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1985)### impl<T> Send for LinkedList<T>where T: [Send](../../marker/trait.send "trait std::marker::Send"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1988)### impl<T> Sync for LinkedList<T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), Auto Trait Implementations -------------------------- ### impl<T> RefUnwindSafe for LinkedList<T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<T> Unpin for LinkedList<T> ### impl<T> UnwindSafe for LinkedList<T>where T: [UnwindSafe](../../panic/trait.unwindsafe "trait std::panic::UnwindSafe") + [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::linked_list::Iter Struct std::collections::linked\_list::Iter =========================================== ``` pub struct Iter<'a, T>where    T: 'a,{ /* private fields */ } ``` An iterator over the elements of a `LinkedList`. This `struct` is created by [`LinkedList::iter()`](../struct.linkedlist#method.iter "LinkedList::iter()"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#93)### impl<T> Clone for Iter<'\_, T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#94)#### fn clone(&self) -> Iter<'\_, T> Notable traits for [Iter](struct.iter "struct std::collections::linked_list::Iter")<'a, T> ``` impl<'a, T> Iterator for Iter<'a, T> type Item = &'a T; ``` Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#77)1.17.0 · ### impl<T> Debug for Iter<'\_, T>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#78)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1055)### impl<'a, T> DoubleEndedIterator for Iter<'a, T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1057)#### fn next\_back(&mut self) -> Option<&'a T> Removes and returns an element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1073)### impl<T> ExactSizeIterator for Iter<'\_, T> [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#106)#### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#138)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1025)### impl<'a, T> Iterator for Iter<'a, T> #### type Item = &'a T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1029)#### fn next(&mut self) -> Option<&'a T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1044)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1049)#### fn last(self) -> Option<&'a T> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../../primitive.reference) T>, P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2920-2923)#### fn rposition<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Self: [ExactSizeIterator](../../iter/trait.exactsizeiterator "trait std::iter::ExactSizeIterator") + [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Searches for an element in an iterator from the right, returning its index. [Read more](../../iter/trait.iterator#method.rposition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)#### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)#### fn cycle(self) -> Cycle<Self>where Self: [Clone](../../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1076)1.26.0 · ### impl<T> FusedIterator for Iter<'\_, T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1991)### impl<T> Send for Iter<'\_, T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1994)### impl<T> Sync for Iter<'\_, T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), Auto Trait Implementations -------------------------- ### impl<'a, T> RefUnwindSafe for Iter<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T> Unpin for Iter<'a, T> ### impl<'a, T> UnwindSafe for Iter<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::linked_list::Cursor Struct std::collections::linked\_list::Cursor ============================================= ``` pub struct Cursor<'a, T>where    T: 'a,{ /* private fields */ } ``` 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) A cursor over a `LinkedList`. A `Cursor` is like an iterator, except that it can freely seek back-and-forth. Cursors always rest between two elements in the list, and index in a logically circular way. To accommodate this, there is a “ghost” non-element that yields `None` between the head and tail of the list. When created, cursors start at the front of the list, or the “ghost” non-element if the list is empty. Implementations --------------- [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1187)### impl<'a, T> Cursor<'a, T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1194)#### pub fn index(&self) -> Option<usize> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Returns the cursor position index within the `LinkedList`. This returns `None` if the cursor is currently pointing to the “ghost” non-element. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1205)#### pub fn move\_next(&mut self) 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Moves the cursor to the next element of the `LinkedList`. If the cursor is pointing to the “ghost” non-element then this will move it to the first element of the `LinkedList`. If it is pointing to the last element of the `LinkedList` then this will move it to the “ghost” non-element. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1227)#### pub fn move\_prev(&mut self) 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Moves the cursor to the previous element of the `LinkedList`. If the cursor is pointing to the “ghost” non-element then this will move it to the last element of the `LinkedList`. If it is pointing to the first element of the `LinkedList` then this will move it to the “ghost” non-element. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1249)#### pub fn current(&self) -> Option<&'a T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Returns a reference to the element that the cursor is currently pointing to. This returns `None` if the cursor is currently pointing to the “ghost” non-element. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1260)#### pub fn peek\_next(&self) -> Option<&'a T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Returns a reference to the next element. If the cursor is pointing to the “ghost” non-element then this returns the first element of the `LinkedList`. If it is pointing to the last element of the `LinkedList` then this returns `None`. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1277)#### pub fn peek\_prev(&self) -> Option<&'a T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Returns a reference to the previous element. If the cursor is pointing to the “ghost” non-element then this returns the last element of the `LinkedList`. If it is pointing to the first element of the `LinkedList` then this returns `None`. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1291)#### pub fn front(&self) -> Option<&'a T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Provides a reference to the front element of the cursor’s parent list, or None if the list is empty. [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1299)#### pub fn back(&self) -> Option<&'a T> 🔬This is a nightly-only experimental API. (`linked_list_cursors` [#58533](https://github.com/rust-lang/rust/issues/58533)) Provides a reference to the back element of the cursor’s parent list, or None if the list is empty. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1149)### impl<T> Clone for Cursor<'\_, T> [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1150)#### fn clone(&self) -> Cursor<'\_, T> Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1157)### impl<T> Debug for Cursor<'\_, T>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1158)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#2003)### impl<T> Send for Cursor<'\_, T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#2006)### impl<T> Sync for Cursor<'\_, T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), Auto Trait Implementations -------------------------- ### impl<'a, T> RefUnwindSafe for Cursor<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T> Unpin for Cursor<'a, T> ### impl<'a, T> UnwindSafe for Cursor<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Struct std::collections::binary_heap::BinaryHeap Struct std::collections::binary\_heap::BinaryHeap ================================================= ``` pub struct BinaryHeap<T> { /* private fields */ } ``` A priority queue implemented with a binary heap. This will be a max-heap. It is a logic error for an item to be modified in such a way that the item’s ordering relative to any other item, as determined by the [`Ord`](../../cmp/trait.ord) trait, changes while it is in the heap. This is normally only possible through [`Cell`](../../cell/struct.cell), [`RefCell`](../../cell/struct.refcell), global state, I/O, or unsafe code. The behavior resulting from such a logic error is not specified, but will be encapsulated to the `BinaryHeap` that observed the logic error and not result in undefined behavior. This could include panics, incorrect results, aborts, memory leaks, and non-termination. Examples -------- ``` use std::collections::BinaryHeap; // Type inference lets us omit an explicit type signature (which // would be `BinaryHeap<i32>` in this example). let mut heap = BinaryHeap::new(); // We can use peek to look at the next item in the heap. In this case, // there's no items in there yet so we get None. assert_eq!(heap.peek(), None); // Let's add some scores... heap.push(1); heap.push(5); heap.push(2); // Now peek shows the most important item in the heap. assert_eq!(heap.peek(), Some(&5)); // We can check the length of a heap. assert_eq!(heap.len(), 3); // We can iterate over the items in the heap, although they are returned in // a random order. for x in &heap { println!("{x}"); } // If we instead pop these scores, they should come back in order. assert_eq!(heap.pop(), Some(5)); assert_eq!(heap.pop(), Some(2)); assert_eq!(heap.pop(), Some(1)); assert_eq!(heap.pop(), None); // We can clear the heap of any remaining items. heap.clear(); // The heap should now be empty. assert!(heap.is_empty()) ``` A `BinaryHeap` with a known list of items can be initialized from an array: ``` use std::collections::BinaryHeap; let heap = BinaryHeap::from([1, 5, 2]); ``` ### Min-heap Either [`core::cmp::Reverse`](../../cmp/struct.reverse) or a custom [`Ord`](../../cmp/trait.ord) implementation can be used to make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest value instead of the greatest one. ``` use std::collections::BinaryHeap; use std::cmp::Reverse; let mut heap = BinaryHeap::new(); // Wrap values in `Reverse` heap.push(Reverse(1)); heap.push(Reverse(5)); heap.push(Reverse(2)); // If we pop these scores now, they should come back in the reverse order. assert_eq!(heap.pop(), Some(Reverse(1))); assert_eq!(heap.pop(), Some(Reverse(2))); assert_eq!(heap.pop(), Some(Reverse(5))); assert_eq!(heap.pop(), None); ``` Time complexity --------------- | [push](../struct.binaryheap#method.push) | [pop](../struct.binaryheap#method.pop) | [peek](../struct.binaryheap#method.peek)/[peek\_mut](../struct.binaryheap#method.peek_mut) | | --- | --- | --- | | *O*(1)~ | *O*(log(*n*)) | *O*(1) | The value for `push` is an expected cost; the method documentation gives a more detailed analysis. Implementations --------------- [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#359)### impl<T> BinaryHeap<T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#373)#### pub fn new() -> BinaryHeap<T> Creates an empty `BinaryHeap` as a max-heap. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); heap.push(4); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#394)#### pub fn with\_capacity(capacity: usize) -> BinaryHeap<T> Creates an empty `BinaryHeap` with at least the specified capacity. The binary heap will be able to hold at least `capacity` elements without reallocating. This method is allowed to allocate for more elements than `capacity`. If `capacity` is 0, the binary heap will not allocate. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut heap = BinaryHeap::with_capacity(10); heap.push(4); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#428)1.12.0 · #### pub fn peek\_mut(&mut self) -> Option<PeekMut<'\_, T>> Returns a mutable reference to the greatest item in the binary heap, or `None` if it is empty. Note: If the `PeekMut` value is leaked, the heap may be in an inconsistent state. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); assert!(heap.peek_mut().is_none()); heap.push(1); heap.push(5); heap.push(2); { let mut val = heap.peek_mut().unwrap(); *val = 0; } assert_eq!(heap.peek(), Some(&2)); ``` ##### Time complexity If the item is modified then the worst case time complexity is *O*(log(*n*)), otherwise it’s *O*(1). [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#452)#### pub fn pop(&mut self) -> Option<T> Removes the greatest item from the binary heap and returns it, or `None` if it is empty. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut heap = BinaryHeap::from([1, 3]); assert_eq!(heap.pop(), Some(3)); assert_eq!(heap.pop(), Some(1)); assert_eq!(heap.pop(), None); ``` ##### Time complexity The worst case cost of `pop` on a heap containing *n* elements is *O*(log(*n*)). [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#496)#### pub fn push(&mut self, item: T) Pushes an item onto the binary heap. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); heap.push(3); heap.push(5); heap.push(1); assert_eq!(heap.len(), 3); assert_eq!(heap.peek(), Some(&5)); ``` ##### Time complexity The expected cost of `push`, averaged over every possible ordering of the elements being pushed, and over a sufficiently large number of pushes, is *O*(1). This is the most meaningful cost metric when pushing elements that are *not* already in any sorted pattern. The time complexity degrades if elements are pushed in predominantly ascending order. In the worst case, elements are pushed in ascending sorted order and the amortized cost per push is *O*(log(*n*)) against a heap containing *n* elements. The worst case cost of a *single* call to `push` is *O*(*n*). The worst case occurs when capacity is exhausted and needs a resize. The resize cost has been amortized in the previous figures. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#523)1.5.0 · #### pub fn into\_sorted\_vec(self) -> Vec<T, Global> Notable traits for [Vec](../../vec/struct.vec "struct std::vec::Vec")<[u8](../../primitive.u8), A> ``` impl<A: Allocator> Write for Vec<u8, A> ``` Consumes the `BinaryHeap` and returns a vector in sorted (ascending) order. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut heap = BinaryHeap::from([1, 2, 4, 5, 7]); heap.push(6); heap.push(3); let vec = heap.into_sorted_vec(); assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#742)1.11.0 · #### pub fn append(&mut self, other: &mut BinaryHeap<T>) Moves all the elements of `other` into `self`, leaving `other` empty. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut a = BinaryHeap::from([-10, 1, 2, 3, 3]); let mut b = BinaryHeap::from([-20, 5, 43]); a.append(&mut b); assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]); assert!(b.is_empty()); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#781)#### pub fn drain\_sorted(&mut self) -> DrainSorted<'\_, T> Notable traits for [DrainSorted](struct.drainsorted "struct std::collections::binary_heap::DrainSorted")<'\_, T> ``` impl<T> Iterator for DrainSorted<'_, T>where     T: Ord, type Item = T; ``` 🔬This is a nightly-only experimental API. (`binary_heap_drain_sorted` [#59278](https://github.com/rust-lang/rust/issues/59278)) Clears the binary heap, returning an iterator over the removed elements in heap order. If the iterator is dropped before being fully consumed, it drops the remaining elements in heap order. The returned iterator keeps a mutable borrow on the heap to optimize its implementation. Note: * `.drain_sorted()` is *O*(*n* \* log(*n*)); much slower than `.drain()`. You should use the latter for most cases. ##### Examples Basic usage: ``` #![feature(binary_heap_drain_sorted)] use std::collections::BinaryHeap; let mut heap = BinaryHeap::from([1, 2, 3, 4, 5]); assert_eq!(heap.len(), 5); drop(heap.drain_sorted()); // removes all elements in heap order assert_eq!(heap.len(), 0); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#805-807)#### pub fn retain<F>(&mut self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`binary_heap_retain` [#71503](https://github.com/rust-lang/rust/issues/71503)) Retains only the elements specified by the predicate. In other words, remove all elements `e` for which `f(&e)` returns `false`. The elements are visited in unsorted (and unspecified) order. ##### Examples Basic usage: ``` #![feature(binary_heap_retain)] use std::collections::BinaryHeap; let mut heap = BinaryHeap::from([-10, -5, 1, 2, 4, 13]); heap.retain(|x| x % 2 == 0); // only keep even numbers assert_eq!(heap.into_sorted_vec(), [-10, 2, 4]) ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#824)### impl<T> BinaryHeap<T> [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#842)#### pub fn iter(&self) -> Iter<'\_, T> Notable traits for [Iter](struct.iter "struct std::collections::binary_heap::Iter")<'a, T> ``` impl<'a, T> Iterator for Iter<'a, T> type Item = &'a T; ``` Returns an iterator visiting all values in the underlying vector, in arbitrary order. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let heap = BinaryHeap::from([1, 2, 3, 4]); // Print 1, 2, 3, 4 in arbitrary order for x in heap.iter() { println!("{x}"); } ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#861)#### pub fn into\_iter\_sorted(self) -> IntoIterSorted<T> Notable traits for [IntoIterSorted](struct.intoitersorted "struct std::collections::binary_heap::IntoIterSorted")<T> ``` impl<T> Iterator for IntoIterSorted<T>where     T: Ord, type Item = T; ``` 🔬This is a nightly-only experimental API. (`binary_heap_into_iter_sorted` [#59278](https://github.com/rust-lang/rust/issues/59278)) Returns an iterator which retrieves elements in heap order. This method consumes the original heap. ##### Examples Basic usage: ``` #![feature(binary_heap_into_iter_sorted)] use std::collections::BinaryHeap; let heap = BinaryHeap::from([1, 2, 3, 4, 5]); assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), [5, 4]); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#888)#### pub fn peek(&self) -> Option<&T> Returns the greatest item in the binary heap, or `None` if it is empty. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); assert_eq!(heap.peek(), None); heap.push(1); heap.push(5); heap.push(2); assert_eq!(heap.peek(), Some(&5)); ``` ##### Time complexity Cost is *O*(1) in the worst case. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#906)#### pub fn capacity(&self) -> usize Returns the number of elements the binary heap can hold without reallocating. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut heap = BinaryHeap::with_capacity(100); assert!(heap.capacity() >= 100); heap.push(4); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#937)#### pub fn reserve\_exact(&mut self, additional: usize) Reserves the minimum capacity for at least `additional` elements more than the current length. Unlike [`reserve`](../struct.binaryheap#method.reserve), this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling `reserve_exact`, capacity will be greater than or equal to `self.len() + additional`. Does nothing if the capacity is already sufficient. ##### Panics Panics if the new capacity overflows [`usize`](../../primitive.usize "usize"). ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); heap.reserve_exact(100); assert!(heap.capacity() >= 100); heap.push(4); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#963)#### pub fn reserve(&mut self, additional: usize) Reserves capacity for at least `additional` elements more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. After calling `reserve`, capacity will be greater than or equal to `self.len() + additional`. Does nothing if capacity is already sufficient. ##### Panics Panics if the new capacity overflows [`usize`](../../primitive.usize "usize"). ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); heap.reserve(100); assert!(heap.capacity() >= 100); heap.push(4); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1005)1.63.0 · #### pub fn try\_reserve\_exact( &mut self, additional: usize) -> Result<(), TryReserveError> Tries to reserve the minimum capacity for at least `additional` elements more than the current length. Unlike [`try_reserve`](../struct.binaryheap#method.try_reserve), this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling `try_reserve_exact`, capacity will be greater than or equal to `self.len() + additional` if it returns `Ok(())`. Does nothing if the capacity is already sufficient. Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer [`try_reserve`](../struct.binaryheap#method.try_reserve) if future insertions are expected. ##### Errors If the capacity overflows, or the allocator reports a failure, then an error is returned. ##### Examples ``` use std::collections::BinaryHeap; use std::collections::TryReserveError; fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> { let mut heap = BinaryHeap::new(); // Pre-reserve the memory, exiting if we can't heap.try_reserve_exact(data.len())?; // Now we know this can't OOM in the middle of our complex work heap.extend(data.iter()); Ok(heap.pop()) } ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1041)1.63.0 · #### pub fn try\_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> Tries to reserve capacity for at least `additional` elements more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. After calling `try_reserve`, capacity will be greater than or equal to `self.len() + additional` if it returns `Ok(())`. Does nothing if capacity is already sufficient. This method preserves the contents even if an error occurs. ##### Errors If the capacity overflows, or the allocator reports a failure, then an error is returned. ##### Examples ``` use std::collections::BinaryHeap; use std::collections::TryReserveError; fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> { let mut heap = BinaryHeap::new(); // Pre-reserve the memory, exiting if we can't heap.try_reserve(data.len())?; // Now we know this can't OOM in the middle of our complex work heap.extend(data.iter()); Ok(heap.pop()) } ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1060)#### pub fn shrink\_to\_fit(&mut self) Discards as much additional capacity as possible. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100); assert!(heap.capacity() >= 100); heap.shrink_to_fit(); assert!(heap.capacity() == 0); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1083)1.56.0 · #### pub fn shrink\_to(&mut self, min\_capacity: usize) Discards capacity with a lower bound. The capacity will remain at least as large as both the length and the supplied value. If the current capacity is less than the lower limit, this is a no-op. ##### Examples ``` use std::collections::BinaryHeap; let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100); assert!(heap.capacity() >= 100); heap.shrink_to(10); assert!(heap.capacity() >= 10); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1105)#### pub fn as\_slice(&self) -> &[T] Notable traits for &[[u8](../../primitive.u8)] ``` impl Read for &[u8] impl Write for &mut [u8] ``` 🔬This is a nightly-only experimental API. (`binary_heap_as_slice` [#83659](https://github.com/rust-lang/rust/issues/83659)) Returns a slice of all values in the underlying vector, in arbitrary order. ##### Examples Basic usage: ``` #![feature(binary_heap_as_slice)] use std::collections::BinaryHeap; use std::io::{self, Write}; let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]); io::sink().write(heap.as_slice()).unwrap(); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1128)1.5.0 · #### pub fn into\_vec(self) -> Vec<T, Global> Notable traits for [Vec](../../vec/struct.vec "struct std::vec::Vec")<[u8](../../primitive.u8), A> ``` impl<A: Allocator> Write for Vec<u8, A> ``` Consumes the `BinaryHeap` and returns the underlying vector in arbitrary order. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let heap = BinaryHeap::from([1, 2, 3, 4, 5, 6, 7]); let vec = heap.into_vec(); // Will print in some order for x in vec { println!("{x}"); } ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1146)#### pub fn len(&self) -> usize Returns the length of the binary heap. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let heap = BinaryHeap::from([1, 3]); assert_eq!(heap.len(), 2); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1170)#### pub fn is\_empty(&self) -> bool Checks if the binary heap is empty. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); assert!(heap.is_empty()); heap.push(3); heap.push(5); heap.push(1); assert!(!heap.is_empty()); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1199)1.6.0 · #### pub fn drain(&mut self) -> Drain<'\_, T> Notable traits for [Drain](struct.drain "struct std::collections::binary_heap::Drain")<'\_, T> ``` impl<T> Iterator for Drain<'_, T> type Item = T; ``` Clears the binary heap, returning an iterator over the removed elements in arbitrary order. If the iterator is dropped before being fully consumed, it drops the remaining elements in arbitrary order. The returned iterator keeps a mutable borrow on the heap to optimize its implementation. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut heap = BinaryHeap::from([1, 3]); assert!(!heap.is_empty()); for x in heap.drain() { println!("{x}"); } assert!(heap.is_empty()); ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1220)#### pub fn clear(&mut self) Drops all items from the binary heap. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let mut heap = BinaryHeap::from([1, 3]); assert!(!heap.is_empty()); heap.clear(); assert!(heap.is_empty()); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#333)### impl<T> Clone for BinaryHeap<T>where T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#334)#### fn clone(&self) -> BinaryHeap<T> Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#338)#### fn clone\_from(&mut self, source: &BinaryHeap<T>) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#353)1.4.0 · ### impl<T> Debug for BinaryHeap<T>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#354)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#344)### impl<T> Default for BinaryHeap<T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#347)#### fn default() -> BinaryHeap<T> Creates an empty `BinaryHeap<T>`. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1707)1.2.0 · ### impl<'a, T> Extend<&'a T> for BinaryHeap<T>where T: 'a + [Ord](../../cmp/trait.ord "trait std::cmp::Ord") + [Copy](../../marker/trait.copy "trait std::marker::Copy"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1708)#### fn extend<I>(&mut self, iter: I)where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = [&'a](../../primitive.reference) T>, Extends a collection with the contents of an iterator. [Read more](../../iter/trait.extend#tymethod.extend) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1713)#### fn extend\_one(&mut self, &'a T) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Extends a collection with exactly one element. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1718)#### fn extend\_reserve(&mut self, additional: usize) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Reserves capacity in a collection for the given number of additional elements. [Read more](../../iter/trait.extend#method.extend_reserve) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1658)### impl<T> Extend<T> for BinaryHeap<T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1660)#### fn extend<I>(&mut self, iter: I)where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = T>, Extends a collection with the contents of an iterator. [Read more](../../iter/trait.extend#tymethod.extend) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1665)#### fn extend\_one(&mut self, item: T) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Extends a collection with exactly one element. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1670)#### fn extend\_reserve(&mut self, additional: usize) 🔬This is a nightly-only experimental API. (`extend_one` [#72631](https://github.com/rust-lang/rust/issues/72631)) Reserves capacity in a collection for the given number of additional elements. [Read more](../../iter/trait.extend#method.extend_reserve) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1586)1.56.0 · ### impl<T, const N: usize> From<[T; N]> for BinaryHeap<T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1596)#### fn from(arr: [T; N]) -> BinaryHeap<T> ``` use std::collections::BinaryHeap; let mut h1 = BinaryHeap::from([1, 4, 2, 3]); let mut h2: BinaryHeap<_> = [1, 4, 2, 3].into(); while let Some((a, b)) = h1.pop().zip(h2.pop()) { assert_eq!(a, b); } ``` [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1602)1.5.0 · ### impl<T> From<BinaryHeap<T>> for Vec<T, Global> [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1607)#### fn from(heap: BinaryHeap<T>) -> Vec<T, Global> Notable traits for [Vec](../../vec/struct.vec "struct std::vec::Vec")<[u8](../../primitive.u8), A> ``` impl<A: Allocator> Write for Vec<u8, A> ``` Converts a `BinaryHeap<T>` into a `Vec<T>`. This conversion requires no data movement or allocation, and has constant time complexity. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1574)1.5.0 · ### impl<T> From<Vec<T, Global>> for BinaryHeap<T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1578)#### fn from(vec: Vec<T, Global>) -> BinaryHeap<T> Converts a `Vec<T>` into a `BinaryHeap<T>`. This conversion happens in-place, and has *O*(*n*) time complexity. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1613)### impl<T> FromIterator<T> for BinaryHeap<T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1614)#### fn from\_iter<I>(iter: I) -> BinaryHeap<T>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = T>, Creates a value from an iterator. [Read more](../../iter/trait.fromiterator#tymethod.from_iter) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1648)### impl<'a, T> IntoIterator for &'a BinaryHeap<T> #### type Item = &'a T The type of the elements being iterated over. #### type IntoIter = Iter<'a, T> Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1652)#### fn into\_iter(self) -> Iter<'a, T> Notable traits for [Iter](struct.iter "struct std::collections::binary_heap::Iter")<'a, T> ``` impl<'a, T> Iterator for Iter<'a, T> type Item = &'a T; ``` Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1620)### impl<T> IntoIterator for BinaryHeap<T> [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1642)#### fn into\_iter(self) -> IntoIter<T> Notable traits for [IntoIter](struct.intoiter "struct std::collections::binary_heap::IntoIter")<T> ``` impl<T> Iterator for IntoIter<T> type Item = T; ``` Creates a consuming iterator, that is, one that moves each value out of the binary heap in arbitrary order. The binary heap cannot be used after calling this. ##### Examples Basic usage: ``` use std::collections::BinaryHeap; let heap = BinaryHeap::from([1, 2, 3, 4]); // Print 1, 2, 3, 4 in arbitrary order for x in heap.into_iter() { // x has type i32, not &i32 println!("{x}"); } ``` #### type Item = T The type of the elements being iterated over. #### type IntoIter = IntoIter<T> Which kind of iterator are we turning this into? Auto Trait Implementations -------------------------- ### impl<T> RefUnwindSafe for BinaryHeap<T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<T> Send for BinaryHeap<T>where T: [Send](../../marker/trait.send "trait std::marker::Send"), ### impl<T> Sync for BinaryHeap<T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<T> Unpin for BinaryHeap<T>where T: [Unpin](../../marker/trait.unpin "trait std::marker::Unpin"), ### impl<T> UnwindSafe for BinaryHeap<T>where T: [UnwindSafe](../../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Module std::collections::binary_heap Module std::collections::binary\_heap ===================================== A priority queue implemented with a binary heap. Insertion and popping the largest element have *O*(log(*n*)) time complexity. Checking the largest element is *O*(1). Converting a vector to a binary heap can be done in-place, and has *O*(*n*) complexity. A binary heap can also be converted to a sorted vector in-place, allowing it to be used for an *O*(*n* \* log(*n*)) in-place heapsort. Examples -------- This is a larger example that implements [Dijkstra’s algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm) to solve the [shortest path problem](https://en.wikipedia.org/wiki/Shortest_path_problem) on a [directed graph](https://en.wikipedia.org/wiki/Directed_graph). It shows how to use [`BinaryHeap`](../struct.binaryheap "BinaryHeap") with custom types. ``` use std::cmp::Ordering; use std::collections::BinaryHeap; #[derive(Copy, Clone, Eq, PartialEq)] struct State { cost: usize, position: usize, } // The priority queue depends on `Ord`. // Explicitly implement the trait so the queue becomes a min-heap // instead of a max-heap. impl Ord for State { fn cmp(&self, other: &Self) -> Ordering { // Notice that the we flip the ordering on costs. // In case of a tie we compare positions - this step is necessary // to make implementations of `PartialEq` and `Ord` consistent. other.cost.cmp(&self.cost) .then_with(|| self.position.cmp(&other.position)) } } // `PartialOrd` needs to be implemented as well. impl PartialOrd for State { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } // Each node is represented as a `usize`, for a shorter implementation. struct Edge { node: usize, cost: usize, } // Dijkstra's shortest path algorithm. // Start at `start` and use `dist` to track the current shortest distance // to each node. This implementation isn't memory-efficient as it may leave duplicate // nodes in the queue. It also uses `usize::MAX` as a sentinel value, // for a simpler implementation. fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> { // dist[node] = current shortest distance from `start` to `node` let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect(); let mut heap = BinaryHeap::new(); // We're at `start`, with a zero cost dist[start] = 0; heap.push(State { cost: 0, position: start }); // Examine the frontier with lower cost nodes first (min-heap) while let Some(State { cost, position }) = heap.pop() { // Alternatively we could have continued to find all shortest paths if position == goal { return Some(cost); } // Important as we may have already found a better way if cost > dist[position] { continue; } // For each node we can reach, see if we can find a way with // a lower cost going through this node for edge in &adj_list[position] { let next = State { cost: cost + edge.cost, position: edge.node }; // If so, add it to the frontier and continue if next.cost < dist[next.position] { heap.push(next); // Relaxation, we have now found a better way dist[next.position] = next.cost; } } } // Goal not reachable None } fn main() { // This is the directed graph we're going to use. // The node numbers correspond to the different states, // and the edge weights symbolize the cost of moving // from one node to another. // Note that the edges are one-way. // // 7 // +-----------------+ // | | // v 1 2 | 2 // 0 -----> 1 -----> 3 ---> 4 // | ^ ^ ^ // | | 1 | | // | | | 3 | 1 // +------> 2 -------+ | // 10 | | // +---------------+ // // The graph is represented as an adjacency list where each index, // corresponding to a node value, has a list of outgoing edges. // Chosen for its efficiency. let graph = vec![ // Node 0 vec![Edge { node: 2, cost: 10 }, Edge { node: 1, cost: 1 }], // Node 1 vec![Edge { node: 3, cost: 2 }], // Node 2 vec![Edge { node: 1, cost: 1 }, Edge { node: 3, cost: 3 }, Edge { node: 4, cost: 1 }], // Node 3 vec![Edge { node: 0, cost: 7 }, Edge { node: 4, cost: 2 }], // Node 4 vec![]]; assert_eq!(shortest_path(&graph, 0, 1), Some(1)); assert_eq!(shortest_path(&graph, 0, 3), Some(3)); assert_eq!(shortest_path(&graph, 3, 0), Some(7)); assert_eq!(shortest_path(&graph, 0, 4), Some(5)); assert_eq!(shortest_path(&graph, 4, 0), None); } ``` Structs ------- [DrainSorted](struct.drainsorted "std::collections::binary_heap::DrainSorted struct")Experimental A draining iterator over the elements of a `BinaryHeap`. [IntoIterSorted](struct.intoitersorted "std::collections::binary_heap::IntoIterSorted struct")Experimental [BinaryHeap](struct.binaryheap "std::collections::binary_heap::BinaryHeap struct") A priority queue implemented with a binary heap. [Drain](struct.drain "std::collections::binary_heap::Drain struct") A draining iterator over the elements of a `BinaryHeap`. [IntoIter](struct.intoiter "std::collections::binary_heap::IntoIter struct") An owning iterator over the elements of a `BinaryHeap`. [Iter](struct.iter "std::collections::binary_heap::Iter struct") An iterator over the elements of a `BinaryHeap`. [PeekMut](struct.peekmut "std::collections::binary_heap::PeekMut struct") Structure wrapping a mutable reference to the greatest item on a `BinaryHeap`. rust Struct std::collections::binary_heap::PeekMut Struct std::collections::binary\_heap::PeekMut ============================================== ``` pub struct PeekMut<'a, T>where    T: 'a + Ord,{ /* private fields */ } ``` Structure wrapping a mutable reference to the greatest item on a `BinaryHeap`. This `struct` is created by the [`peek_mut`](../struct.binaryheap#method.peek_mut) method on [`BinaryHeap`](../struct.binaryheap "BinaryHeap"). See its documentation for more. Implementations --------------- [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#322)### impl<'a, T> PeekMut<'a, T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#325)1.18.0 · #### pub fn pop(this: PeekMut<'a, T>) -> T Removes the peeked value from the heap and returns it. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#286)1.17.0 · ### impl<T> Debug for PeekMut<'\_, T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord") + [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#287)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#303)### impl<T> Deref for PeekMut<'\_, T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), #### type Target = T The resulting type after dereferencing. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#305)#### fn deref(&self) -> &T Dereferences the value. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#313)### impl<T> DerefMut for PeekMut<'\_, T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#314)#### fn deref\_mut(&mut self) -> &mut T Mutably dereferences the value. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#293)### impl<T> Drop for PeekMut<'\_, T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#294)#### fn drop(&mut self) Executes the destructor for this type. [Read more](../../ops/trait.drop#tymethod.drop) Auto Trait Implementations -------------------------- ### impl<'a, T> RefUnwindSafe for PeekMut<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T> Send for PeekMut<'a, T>where T: [Send](../../marker/trait.send "trait std::marker::Send"), ### impl<'a, T> Sync for PeekMut<'a, T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T> Unpin for PeekMut<'a, T> ### impl<'a, T> !UnwindSafe for PeekMut<'a, T> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Struct std::collections::binary_heap::IntoIter Struct std::collections::binary\_heap::IntoIter =============================================== ``` pub struct IntoIter<T> { /* private fields */ } ``` An owning iterator over the elements of a `BinaryHeap`. This `struct` is created by [`BinaryHeap::into_iter()`](../struct.binaryheap#method.into_iter "BinaryHeap::into_iter()") (provided by the [`IntoIterator`](../../iter/trait.intoiterator) trait). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1369)### impl<T> Clone for IntoIter<T>where T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1369)#### fn clone(&self) -> IntoIter<T> Notable traits for [IntoIter](struct.intoiter "struct std::collections::binary_heap::IntoIter")<T> ``` impl<T> Iterator for IntoIter<T> type Item = T; ``` Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1375)1.17.0 · ### impl<T> Debug for IntoIter<T>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1376)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1397)### impl<T> DoubleEndedIterator for IntoIter<T> [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1399)#### fn next\_back(&mut self) -> Option<T> Removes and returns an element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1405)### impl<T> ExactSizeIterator for IntoIter<T> [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1406)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#106)#### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1382)### impl<T> Iterator for IntoIter<T> #### type Item = T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1386)#### fn next(&mut self) -> Option<T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1391)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../../primitive.reference) T>, P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2920-2923)#### fn rposition<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Self: [ExactSizeIterator](../../iter/trait.exactsizeiterator "trait std::iter::ExactSizeIterator") + [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Searches for an element in an iterator from the right, returning its index. [Read more](../../iter/trait.iterator#method.rposition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)#### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1412)1.26.0 · ### impl<T> FusedIterator for IntoIter<T> Auto Trait Implementations -------------------------- ### impl<T> RefUnwindSafe for IntoIter<T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<T> Send for IntoIter<T>where T: [Send](../../marker/trait.send "trait std::marker::Send"), ### impl<T> Sync for IntoIter<T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<T> Unpin for IntoIter<T>where T: [Unpin](../../marker/trait.unpin "trait std::marker::Unpin"), ### impl<T> UnwindSafe for IntoIter<T>where T: [UnwindSafe](../../panic/trait.unwindsafe "trait std::panic::UnwindSafe") + [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::binary_heap::DrainSorted Struct std::collections::binary\_heap::DrainSorted ================================================== ``` pub struct DrainSorted<'a, T>where    T: Ord,{ /* private fields */ } ``` 🔬This is a nightly-only experimental API. (`binary_heap_drain_sorted` [#59278](https://github.com/rust-lang/rust/issues/59278)) A draining iterator over the elements of a `BinaryHeap`. This `struct` is created by [`BinaryHeap::drain_sorted()`](../struct.binaryheap#method.drain_sorted "BinaryHeap::drain_sorted()"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1523)### impl<'a, T> Debug for DrainSorted<'a, T>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug") + [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1523)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1529)### impl<'a, T> Drop for DrainSorted<'a, T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1531)#### fn drop(&mut self) Removes heap elements in heap order. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1565)### impl<T> ExactSizeIterator for DrainSorted<'\_, T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#106)1.0.0 · #### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#138)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1549)### impl<T> Iterator for DrainSorted<'\_, T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), #### type Item = T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1553)#### fn next(&mut self) -> Option<T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1558)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1568)### impl<T> FusedIterator for DrainSorted<'\_, T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1571)### impl<T> TrustedLen for DrainSorted<'\_, T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), Auto Trait Implementations -------------------------- ### impl<'a, T> RefUnwindSafe for DrainSorted<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T> Send for DrainSorted<'a, T>where T: [Send](../../marker/trait.send "trait std::marker::Send"), ### impl<'a, T> Sync for DrainSorted<'a, T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T> Unpin for DrainSorted<'a, T> ### impl<'a, T> !UnwindSafe for DrainSorted<'a, T> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::binary_heap::IntoIterSorted Struct std::collections::binary\_heap::IntoIterSorted ===================================================== ``` pub struct IntoIterSorted<T> { /* private fields */ } ``` 🔬This is a nightly-only experimental API. (`binary_heap_into_iter_sorted` [#59278](https://github.com/rust-lang/rust/issues/59278)) Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1441)### impl<T> Clone for IntoIterSorted<T>where T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1441)#### fn clone(&self) -> IntoIterSorted<T> Notable traits for [IntoIterSorted](struct.intoitersorted "struct std::collections::binary_heap::IntoIterSorted")<T> ``` impl<T> Iterator for IntoIterSorted<T>where     T: Ord, type Item = T; ``` Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1441)### impl<T> Debug for IntoIterSorted<T>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1441)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1463)### impl<T> ExactSizeIterator for IntoIterSorted<T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#106)1.0.0 · #### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#138)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1447)### impl<T> Iterator for IntoIterSorted<T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), #### type Item = T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1451)#### fn next(&mut self) -> Option<T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1456)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1466)### impl<T> FusedIterator for IntoIterSorted<T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1469)### impl<T> TrustedLen for IntoIterSorted<T>where T: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), Auto Trait Implementations -------------------------- ### impl<T> RefUnwindSafe for IntoIterSorted<T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<T> Send for IntoIterSorted<T>where T: [Send](../../marker/trait.send "trait std::marker::Send"), ### impl<T> Sync for IntoIterSorted<T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<T> Unpin for IntoIterSorted<T>where T: [Unpin](../../marker/trait.unpin "trait std::marker::Unpin"), ### impl<T> UnwindSafe for IntoIterSorted<T>where T: [UnwindSafe](../../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::binary_heap::Drain Struct std::collections::binary\_heap::Drain ============================================ ``` pub struct Drain<'a, T>where    T: 'a,{ /* private fields */ } ``` A draining iterator over the elements of a `BinaryHeap`. This `struct` is created by [`BinaryHeap::drain()`](../struct.binaryheap#method.drain "BinaryHeap::drain()"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1478)### impl<'a, T> Debug for Drain<'a, T>where T: 'a + [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1478)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1499)### impl<T> DoubleEndedIterator for Drain<'\_, T> [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1501)#### fn next\_back(&mut self) -> Option<T> Removes and returns an element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1507)### impl<T> ExactSizeIterator for Drain<'\_, T> [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1508)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#106)1.0.0 · #### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1484)### impl<T> Iterator for Drain<'\_, T> #### type Item = T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1488)#### fn next(&mut self) -> Option<T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1493)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../../primitive.reference) T>, P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2920-2923)1.0.0 · #### fn rposition<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Self: [ExactSizeIterator](../../iter/trait.exactsizeiterator "trait std::iter::ExactSizeIterator") + [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Searches for an element in an iterator from the right, returning its index. [Read more](../../iter/trait.iterator#method.rposition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)#### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)#### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)1.0.0 · #### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1514)1.26.0 · ### impl<T> FusedIterator for Drain<'\_, T> Auto Trait Implementations -------------------------- ### impl<'a, T> RefUnwindSafe for Drain<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T> Send for Drain<'a, T>where T: [Send](../../marker/trait.send "trait std::marker::Send"), ### impl<'a, T> Sync for Drain<'a, T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T> Unpin for Drain<'a, T> ### impl<'a, T> UnwindSafe for Drain<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::collections::binary_heap::Iter Struct std::collections::binary\_heap::Iter =========================================== ``` pub struct Iter<'a, T>where    T: 'a,{ /* private fields */ } ``` An iterator over the elements of a `BinaryHeap`. This `struct` is created by [`BinaryHeap::iter()`](../struct.binaryheap#method.iter "BinaryHeap::iter()"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1317)### impl<T> Clone for Iter<'\_, T> [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1318)#### fn clone(&self) -> Iter<'\_, T> Notable traits for [Iter](struct.iter "struct std::collections::binary_heap::Iter")<'a, T> ``` impl<'a, T> Iterator for Iter<'a, T> type Item = &'a T; ``` Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1309)1.17.0 · ### impl<T> Debug for Iter<'\_, T>where T: [Debug](../../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1310)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1344)### impl<'a, T> DoubleEndedIterator for Iter<'a, T> [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1346)#### fn next\_back(&mut self) -> Option<&'a T> Removes and returns an element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1352)### impl<T> ExactSizeIterator for Iter<'\_, T> [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1353)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#106)#### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1324)### impl<'a, T> Iterator for Iter<'a, T> #### type Item = &'a T The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1328)#### fn next(&mut self) -> Option<&'a T> Advances the iterator and returns the next value. [Read more](../../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1333)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1338)#### fn last(self) -> Option<&'a T> Consumes the iterator, returning the last element. [Read more](../../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [Filter](../../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../../iter/struct.peekable#method.peek) and [`peek_mut`](../../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [SkipWhile](../../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Notable traits for [TakeWhile](../../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../../primitive.reference) St, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../../option/enum.option#variant.None "None"). [Read more](../../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../../primitive.reference) T>, P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([&](../../primitive.reference)T) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [()](../../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../../ops/trait.try "trait std::ops::Try")<Output = [bool](../../primitive.bool)>, <R as [Try](../../ops/trait.try "trait std::ops::Try")>::[Residual](../../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../../ops/trait.residual "trait std::ops::Residual")<[Option](../../option/enum.option "enum std::option::Option")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2920-2923)#### fn rposition<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../../primitive.bool), Self: [ExactSizeIterator](../../iter/trait.exactsizeiterator "trait std::iter::ExactSizeIterator") + [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Searches for an element in an iterator from the right, returning its index. [Read more](../../iter/trait.iterator#method.rposition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)#### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../../default/trait.default "trait std::default::Default") + [Extend](../../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Copied](../../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../../primitive.reference) T>, Notable traits for [Cloned](../../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)#### fn cycle(self) -> Cycle<Self>where Self: [Clone](../../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../../iter/trait.product "trait std::iter::Product")<Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another. [Read more](../../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../../iter/trait.iterator "Iterator") are [lexicographically](../../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../../option/enum.option "enum std::option::Option")<[Ordering](../../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1359)1.26.0 · ### impl<T> FusedIterator for Iter<'\_, T> Auto Trait Implementations -------------------------- ### impl<'a, T> RefUnwindSafe for Iter<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, T> Send for Iter<'a, T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T> Sync for Iter<'a, T>where T: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, T> Unpin for Iter<'a, T> ### impl<'a, T> UnwindSafe for Iter<'a, T>where T: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::fs::Permissions Struct std::fs::Permissions =========================== ``` pub struct Permissions(_); ``` Representation of the various permissions on a file. This module only currently provides one bit of information, [`Permissions::readonly`](struct.permissions#method.readonly "Permissions::readonly"), which is exposed on all currently supported platforms. Unix-specific functionality, such as mode bits, is available through the [`PermissionsExt`](../os/unix/fs/trait.permissionsext) trait. Implementations --------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#1365-1420)### impl Permissions [source](https://doc.rust-lang.org/src/std/fs.rs.html#1383-1385)#### pub fn readonly(&self) -> bool Returns `true` if these permissions describe a readonly (unwritable) file. ##### Examples ``` use std::fs::File; fn main() -> std::io::Result<()> { let mut f = File::create("foo.txt")?; let metadata = f.metadata()?; assert_eq!(false, metadata.permissions().readonly()); Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1417-1419)#### pub fn set\_readonly(&mut self, readonly: bool) Modifies the readonly flag for this set of permissions. If the `readonly` argument is `true`, using the resulting `Permission` will update file permissions to forbid writing. Conversely, if it’s `false`, using the resulting `Permission` will update file permissions to allow writing. This operation does **not** modify the filesystem. To modify the filesystem use the [`set_permissions`](fn.set_permissions "set_permissions") function. ##### Examples ``` use std::fs::File; fn main() -> std::io::Result<()> { let f = File::create("foo.txt")?; let metadata = f.metadata()?; let mut permissions = metadata.permissions(); permissions.set_readonly(true); // filesystem doesn't change assert_eq!(false, metadata.permissions().readonly()); // just this particular `permissions`. assert_eq!(true, permissions.readonly()); Ok(()) } ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#200)### impl Clone for Permissions [source](https://doc.rust-lang.org/src/std/fs.rs.html#200)#### fn clone(&self) -> Permissions Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/fs.rs.html#200)### impl Debug for Permissions [source](https://doc.rust-lang.org/src/std/fs.rs.html#200)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/fs.rs.html#200)### impl PartialEq<Permissions> for Permissions [source](https://doc.rust-lang.org/src/std/fs.rs.html#200)#### fn eq(&self, other: &Permissions) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#289-301)1.1.0 · ### impl PermissionsExt for Permissions Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#290-292)#### fn mode(&self) -> u32 Returns the underlying raw `st_mode` bits that contain the standard Unix permissions for this file. [Read more](../os/unix/fs/trait.permissionsext#tymethod.mode) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#294-296)#### fn set\_mode(&mut self, mode: u32) Sets the underlying raw bits for this set of permissions. [Read more](../os/unix/fs/trait.permissionsext#tymethod.set_mode) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#298-300)#### fn from\_mode(mode: u32) -> Permissions Creates a new instance of `Permissions` from the given set of Unix permission bits. [Read more](../os/unix/fs/trait.permissionsext#tymethod.from_mode) [source](https://doc.rust-lang.org/src/std/fs.rs.html#200)### impl Eq for Permissions [source](https://doc.rust-lang.org/src/std/fs.rs.html#200)### impl StructuralEq for Permissions [source](https://doc.rust-lang.org/src/std/fs.rs.html#200)### impl StructuralPartialEq for Permissions Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for Permissions ### impl Send for Permissions ### impl Sync for Permissions ### impl Unpin for Permissions ### impl UnwindSafe for Permissions Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Function std::fs::remove_file Function std::fs::remove\_file ============================== ``` pub fn remove_file<P: AsRef<Path>>(path: P) -> Result<()> ``` Removes a file from the filesystem. Note that there is no guarantee that the file is immediately deleted (e.g., depending on platform, other open file descriptors may prevent immediate removal). Platform-specific behavior -------------------------- This function currently corresponds to the `unlink` function on Unix and the `DeleteFile` function on Windows. Note that, this [may change in the future](../io/index#platform-specific-behavior). Errors ------ This function will return an error in the following situations, but is not limited to just these cases: * `path` points to a directory. * The file doesn’t exist. * The user lacks permissions to remove the file. Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { fs::remove_file("a.txt")?; Ok(()) } ``` rust Function std::fs::read Function std::fs::read ====================== ``` pub fn read<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> ``` Read the entire contents of a file into a bytes vector. This is a convenience function for using [`File::open`](struct.file#method.open "File::open") and [`read_to_end`](../io/trait.read#method.read_to_end) with fewer imports and without an intermediate variable. Errors ------ This function will return an error if `path` does not already exist. Other errors may also be returned according to [`OpenOptions::open`](struct.openoptions#method.open "OpenOptions::open"). It will also return an error if it encounters while reading an error of a kind other than [`io::ErrorKind::Interrupted`](../io/enum.errorkind#variant.Interrupted "io::ErrorKind::Interrupted"). Examples -------- ``` use std::fs; use std::net::SocketAddr; fn main() -> Result<(), Box<dyn std::error::Error + 'static>> { let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?; Ok(()) } ``` rust Module std::fs Module std::fs ============== Filesystem manipulation operations. This module contains basic methods to manipulate the contents of the local filesystem. All methods in this module represent cross-platform filesystem operations. Extra platform-specific functionality can be found in the extension traits of `std::os::$platform`. Structs ------- [FileTimes](struct.filetimes "std::fs::FileTimes struct")Experimental Representation of the various timestamps on a file. [DirBuilder](struct.dirbuilder "std::fs::DirBuilder struct") A builder used to create directories in various manners. [DirEntry](struct.direntry "std::fs::DirEntry struct") Entries returned by the [`ReadDir`](struct.readdir "ReadDir") iterator. [File](struct.file "std::fs::File struct") An object providing access to an open file on the filesystem. [FileType](struct.filetype "std::fs::FileType struct") A structure representing a type of file with accessors for each file type. It is returned by [`Metadata::file_type`](struct.metadata#method.file_type "Metadata::file_type") method. [Metadata](struct.metadata "std::fs::Metadata struct") Metadata information about a file. [OpenOptions](struct.openoptions "std::fs::OpenOptions struct") Options and flags which can be used to configure how a file is opened. [Permissions](struct.permissions "std::fs::Permissions struct") Representation of the various permissions on a file. [ReadDir](struct.readdir "std::fs::ReadDir struct") Iterator over the entries in a directory. Functions --------- [try\_exists](fn.try_exists "std::fs::try_exists fn")Experimental Returns `Ok(true)` if the path points at an existing entity. [canonicalize](fn.canonicalize "std::fs::canonicalize fn") Returns the canonical, absolute form of a path with all intermediate components normalized and symbolic links resolved. [copy](fn.copy "std::fs::copy fn") Copies the contents of one file to another. This function will also copy the permission bits of the original file to the destination file. [create\_dir](fn.create_dir "std::fs::create_dir fn") Creates a new, empty directory at the provided path [create\_dir\_all](fn.create_dir_all "std::fs::create_dir_all fn") Recursively create a directory and all of its parent components if they are missing. [hard\_link](fn.hard_link "std::fs::hard_link fn") Creates a new hard link on the filesystem. [metadata](fn.metadata "std::fs::metadata fn") Given a path, query the file system to get information about a file, directory, etc. [read](fn.read "std::fs::read fn") Read the entire contents of a file into a bytes vector. [read\_dir](fn.read_dir "std::fs::read_dir fn") Returns an iterator over the entries within a directory. [read\_link](fn.read_link "std::fs::read_link fn") Reads a symbolic link, returning the file that the link points to. [read\_to\_string](fn.read_to_string "std::fs::read_to_string fn") Read the entire contents of a file into a string. [remove\_dir](fn.remove_dir "std::fs::remove_dir fn") Removes an empty directory. [remove\_dir\_all](fn.remove_dir_all "std::fs::remove_dir_all fn") Removes a directory at this path, after removing all its contents. Use carefully! [remove\_file](fn.remove_file "std::fs::remove_file fn") Removes a file from the filesystem. [rename](fn.rename "std::fs::rename fn") Rename a file or directory to a new name, replacing the original file if `to` already exists. [set\_permissions](fn.set_permissions "std::fs::set_permissions fn") Changes the permissions found on a file or a directory. [soft\_link](fn.soft_link "std::fs::soft_link fn")Deprecated Creates a new symbolic link on the filesystem. [symlink\_metadata](fn.symlink_metadata "std::fs::symlink_metadata fn") Query the metadata about a file without following symlinks. [write](fn.write "std::fs::write fn") Write a slice as the entire contents of a file. rust Function std::fs::read_link Function std::fs::read\_link ============================ ``` pub fn read_link<P: AsRef<Path>>(path: P) -> Result<PathBuf> ``` Reads a symbolic link, returning the file that the link points to. Platform-specific behavior -------------------------- This function currently corresponds to the `readlink` function on Unix and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows. Note that, this [may change in the future](../io/index#platform-specific-behavior). Errors ------ This function will return an error in the following situations, but is not limited to just these cases: * `path` is not a symbolic link. * `path` does not exist. Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { let path = fs::read_link("a.txt")?; Ok(()) } ``` rust Struct std::fs::Metadata Struct std::fs::Metadata ======================== ``` pub struct Metadata(_); ``` Metadata information about a file. This structure is returned from the [`metadata`](fn.metadata "metadata") or [`symlink_metadata`](fn.symlink_metadata "symlink_metadata") function or method and represents known metadata about a file such as its permissions, size, modification times, etc. Implementations --------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#1076-1312)### impl Metadata [source](https://doc.rust-lang.org/src/std/fs.rs.html#1093-1095)1.1.0 · #### pub fn file\_type(&self) -> FileType Returns the file type for this metadata. ##### Examples ``` fn main() -> std::io::Result<()> { use std::fs; let metadata = fs::metadata("foo.txt")?; println!("{:?}", metadata.file_type()); Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1116-1118)#### pub fn is\_dir(&self) -> bool Returns `true` if this metadata is for a directory. The result is mutually exclusive to the result of [`Metadata::is_file`](struct.metadata#method.is_file "Metadata::is_file"), and will be false for symlink metadata obtained from [`symlink_metadata`](fn.symlink_metadata "symlink_metadata"). ##### Examples ``` fn main() -> std::io::Result<()> { use std::fs; let metadata = fs::metadata("foo.txt")?; assert!(!metadata.is_dir()); Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1145-1147)#### pub fn is\_file(&self) -> bool Returns `true` if this metadata is for a regular file. The result is mutually exclusive to the result of [`Metadata::is_dir`](struct.metadata#method.is_dir "Metadata::is_dir"), and will be false for symlink metadata obtained from [`symlink_metadata`](fn.symlink_metadata "symlink_metadata"). When the goal is simply to read from (or write to) the source, the most reliable way to test the source can be read (or written to) is to open it. Only using `is_file` can break workflows like `diff <( prog_a )` on a Unix-like system for example. See [`File::open`](struct.file#method.open "File::open") or [`OpenOptions::open`](struct.openoptions#method.open "OpenOptions::open") for more information. ##### Examples ``` use std::fs; fn main() -> std::io::Result<()> { let metadata = fs::metadata("foo.txt")?; assert!(metadata.is_file()); Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1171-1173)1.58.0 · #### pub fn is\_symlink(&self) -> bool Returns `true` if this metadata is for a symbolic link. ##### Examples ``` use std::fs; use std::path::Path; use std::os::unix::fs::symlink; fn main() -> std::io::Result<()> { let link_path = Path::new("link"); symlink("/origin_does_not_exist/", link_path)?; let metadata = fs::symlink_metadata(link_path)?; assert!(metadata.is_symlink()); Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1191-1193)#### pub fn len(&self) -> u64 Returns the size of the file, in bytes, this metadata is for. ##### Examples ``` use std::fs; fn main() -> std::io::Result<()> { let metadata = fs::metadata("foo.txt")?; assert_eq!(0, metadata.len()); Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1211-1213)#### pub fn permissions(&self) -> Permissions Returns the permissions of the file this metadata is for. ##### Examples ``` use std::fs; fn main() -> std::io::Result<()> { let metadata = fs::metadata("foo.txt")?; assert!(!metadata.permissions().readonly()); Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1242-1244)1.10.0 · #### pub fn modified(&self) -> Result<SystemTime> Returns the last modification time listed in this metadata. The returned value corresponds to the `mtime` field of `stat` on Unix platforms and the `ftLastWriteTime` field on Windows platforms. ##### Errors This field might not be available on all platforms, and will return an `Err` on platforms where it is not available. ##### Examples ``` use std::fs; fn main() -> std::io::Result<()> { let metadata = fs::metadata("foo.txt")?; if let Ok(time) = metadata.modified() { println!("{time:?}"); } else { println!("Not supported on this platform"); } Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1277-1279)1.10.0 · #### pub fn accessed(&self) -> Result<SystemTime> Returns the last access time of this metadata. The returned value corresponds to the `atime` field of `stat` on Unix platforms and the `ftLastAccessTime` field on Windows platforms. Note that not all platforms will keep this field update in a file’s metadata, for example Windows has an option to disable updating this time when files are accessed and Linux similarly has `noatime`. ##### Errors This field might not be available on all platforms, and will return an `Err` on platforms where it is not available. ##### Examples ``` use std::fs; fn main() -> std::io::Result<()> { let metadata = fs::metadata("foo.txt")?; if let Ok(time) = metadata.accessed() { println!("{time:?}"); } else { println!("Not supported on this platform"); } Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1309-1311)1.10.0 · #### pub fn created(&self) -> Result<SystemTime> Returns the creation time listed in this metadata. The returned value corresponds to the `btime` field of `statx` on Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other Unix platforms, and the `ftCreationTime` field on Windows platforms. ##### Errors This field might not be available on all platforms, and will return an `Err` on platforms or filesystems where it is not available. ##### Examples ``` use std::fs; fn main() -> std::io::Result<()> { let metadata = fs::metadata("foo.txt")?; if let Ok(time) = metadata.created() { println!("{time:?}"); } else { println!("Not supported on this platform or filesystem"); } Ok(()) } ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#109)### impl Clone for Metadata [source](https://doc.rust-lang.org/src/std/fs.rs.html#109)#### fn clone(&self) -> Metadata Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/fs.rs.html#1315-1327)1.16.0 · ### impl Debug for Metadata [source](https://doc.rust-lang.org/src/std/fs.rs.html#1316-1326)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#664-717)1.1.0 · ### impl MetadataExt for Metadata Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#665-667)#### fn dev(&self) -> u64 Returns the ID of the device containing the file. [Read more](../os/unix/fs/trait.metadataext#tymethod.dev) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#668-670)#### fn ino(&self) -> u64 Returns the inode number. [Read more](../os/unix/fs/trait.metadataext#tymethod.ino) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#671-673)#### fn mode(&self) -> u32 Returns the rights applied to this file. [Read more](../os/unix/fs/trait.metadataext#tymethod.mode) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#674-676)#### fn nlink(&self) -> u64 Returns the number of hard links pointing to this file. [Read more](../os/unix/fs/trait.metadataext#tymethod.nlink) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#677-679)#### fn uid(&self) -> u32 Returns the user ID of the owner of this file. [Read more](../os/unix/fs/trait.metadataext#tymethod.uid) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#680-682)#### fn gid(&self) -> u32 Returns the group ID of the owner of this file. [Read more](../os/unix/fs/trait.metadataext#tymethod.gid) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#683-685)#### fn rdev(&self) -> u64 Returns the device ID of this file (if it is a special one). [Read more](../os/unix/fs/trait.metadataext#tymethod.rdev) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#686-688)#### fn size(&self) -> u64 Returns the total size of this file in bytes. [Read more](../os/unix/fs/trait.metadataext#tymethod.size) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#689-691)#### fn atime(&self) -> i64 Returns the last access time of the file, in seconds since Unix Epoch. [Read more](../os/unix/fs/trait.metadataext#tymethod.atime) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#692-694)#### fn atime\_nsec(&self) -> i64 Returns the last access time of the file, in nanoseconds since [`atime`](../os/unix/fs/trait.metadataext#tymethod.atime). [Read more](../os/unix/fs/trait.metadataext#tymethod.atime_nsec) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#695-697)#### fn mtime(&self) -> i64 Returns the last modification time of the file, in seconds since Unix Epoch. [Read more](../os/unix/fs/trait.metadataext#tymethod.mtime) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#698-700)#### fn mtime\_nsec(&self) -> i64 Returns the last modification time of the file, in nanoseconds since [`mtime`](../os/unix/fs/trait.metadataext#tymethod.mtime). [Read more](../os/unix/fs/trait.metadataext#tymethod.mtime_nsec) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#701-703)#### fn ctime(&self) -> i64 Returns the last status change time of the file, in seconds since Unix Epoch. [Read more](../os/unix/fs/trait.metadataext#tymethod.ctime) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#704-706)#### fn ctime\_nsec(&self) -> i64 Returns the last status change time of the file, in nanoseconds since [`ctime`](../os/unix/fs/trait.metadataext#tymethod.ctime). [Read more](../os/unix/fs/trait.metadataext#tymethod.ctime_nsec) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#707-709)#### fn blksize(&self) -> u64 Returns the block size for filesystem I/O. [Read more](../os/unix/fs/trait.metadataext#tymethod.blksize) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#710-712)#### fn blocks(&self) -> u64 Returns the number of blocks allocated to the file, in 512-byte units. [Read more](../os/unix/fs/trait.metadataext#tymethod.blocks) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#329-397)1.1.0 · ### impl MetadataExt for Metadata Available on **Linux** only. [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#331-333)#### fn as\_raw\_stat(&self) -> &stat 👎Deprecated since 1.8.0: other methods of this trait are now preferred Gain a reference to the underlying `stat` structure which contains the raw information returned by the OS. [Read more](../os/linux/fs/trait.metadataext#tymethod.as_raw_stat) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#334-336)#### fn st\_dev(&self) -> u64 Returns the device ID on which this file resides. [Read more](../os/linux/fs/trait.metadataext#tymethod.st_dev) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#337-339)#### fn st\_ino(&self) -> u64 Returns the inode number. [Read more](../os/linux/fs/trait.metadataext#tymethod.st_ino) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#340-342)#### fn st\_mode(&self) -> u32 Returns the file type and mode. [Read more](../os/linux/fs/trait.metadataext#tymethod.st_mode) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#343-345)#### fn st\_nlink(&self) -> u64 Returns the number of hard links to file. [Read more](../os/linux/fs/trait.metadataext#tymethod.st_nlink) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#346-348)#### fn st\_uid(&self) -> u32 Returns the user ID of the file owner. [Read more](../os/linux/fs/trait.metadataext#tymethod.st_uid) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#349-351)#### fn st\_gid(&self) -> u32 Returns the group ID of the file owner. [Read more](../os/linux/fs/trait.metadataext#tymethod.st_gid) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#352-354)#### fn st\_rdev(&self) -> u64 Returns the device ID that this file represents. Only relevant for special file. [Read more](../os/linux/fs/trait.metadataext#tymethod.st_rdev) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#355-357)#### fn st\_size(&self) -> u64 Returns the size of the file (if it is a regular file or a symbolic link) in bytes. [Read more](../os/linux/fs/trait.metadataext#tymethod.st_size) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#358-365)#### fn st\_atime(&self) -> i64 Returns the last access time of the file, in seconds since Unix Epoch. [Read more](../os/linux/fs/trait.metadataext#tymethod.st_atime) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#366-368)#### fn st\_atime\_nsec(&self) -> i64 Returns the last access time of the file, in nanoseconds since [`st_atime`](../os/linux/fs/trait.metadataext#tymethod.st_atime). [Read more](../os/linux/fs/trait.metadataext#tymethod.st_atime_nsec) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#369-376)#### fn st\_mtime(&self) -> i64 Returns the last modification time of the file, in seconds since Unix Epoch. [Read more](../os/linux/fs/trait.metadataext#tymethod.st_mtime) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#377-379)#### fn st\_mtime\_nsec(&self) -> i64 Returns the last modification time of the file, in nanoseconds since [`st_mtime`](../os/linux/fs/trait.metadataext#tymethod.st_mtime). [Read more](../os/linux/fs/trait.metadataext#tymethod.st_mtime_nsec) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#380-387)#### fn st\_ctime(&self) -> i64 Returns the last status change time of the file, in seconds since Unix Epoch. [Read more](../os/linux/fs/trait.metadataext#tymethod.st_ctime) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#388-390)#### fn st\_ctime\_nsec(&self) -> i64 Returns the last status change time of the file, in nanoseconds since [`st_ctime`](../os/linux/fs/trait.metadataext#tymethod.st_ctime). [Read more](../os/linux/fs/trait.metadataext#tymethod.st_ctime_nsec) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#391-393)#### fn st\_blksize(&self) -> u64 Returns the “preferred” block size for efficient filesystem I/O. [Read more](../os/linux/fs/trait.metadataext#tymethod.st_blksize) [source](https://doc.rust-lang.org/src/std/os/linux/fs.rs.html#394-396)#### fn st\_blocks(&self) -> u64 Returns the number of blocks allocated to the file, 512-byte units. [Read more](../os/linux/fs/trait.metadataext#tymethod.st_blocks) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#430-452)### impl MetadataExt for Metadata Available on **WASI** only. [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#431-433)#### fn dev(&self) -> u64 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Returns the `st_dev` field of the internal `filestat_t` [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#434-436)#### fn ino(&self) -> u64 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Returns the `st_ino` field of the internal `filestat_t` [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#437-439)#### fn nlink(&self) -> u64 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Returns the `st_nlink` field of the internal `filestat_t` [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#440-442)#### fn size(&self) -> u64 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Returns the `st_size` field of the internal `filestat_t` [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#443-445)#### fn atim(&self) -> u64 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Returns the `st_atim` field of the internal `filestat_t` [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#446-448)#### fn mtim(&self) -> u64 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Returns the `st_mtim` field of the internal `filestat_t` [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#449-451)#### fn ctim(&self) -> u64 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Returns the `st_ctim` field of the internal `filestat_t` [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#476-501)1.1.0 · ### impl MetadataExt for Metadata Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#477-479)#### fn file\_attributes(&self) -> u32 Returns the value of the `dwFileAttributes` field of this metadata. [Read more](../os/windows/fs/trait.metadataext#tymethod.file_attributes) [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#480-482)#### fn creation\_time(&self) -> u64 Returns the value of the `ftCreationTime` field of this metadata. [Read more](../os/windows/fs/trait.metadataext#tymethod.creation_time) [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#483-485)#### fn last\_access\_time(&self) -> u64 Returns the value of the `ftLastAccessTime` field of this metadata. [Read more](../os/windows/fs/trait.metadataext#tymethod.last_access_time) [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#486-488)#### fn last\_write\_time(&self) -> u64 Returns the value of the `ftLastWriteTime` field of this metadata. [Read more](../os/windows/fs/trait.metadataext#tymethod.last_write_time) [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#489-491)#### fn file\_size(&self) -> u64 Returns the value of the `nFileSize{High,Low}` fields of this metadata. [Read more](../os/windows/fs/trait.metadataext#tymethod.file_size) [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#492-494)#### fn volume\_serial\_number(&self) -> Option<u32> 🔬This is a nightly-only experimental API. (`windows_by_handle` [#63010](https://github.com/rust-lang/rust/issues/63010)) Returns the value of the `dwVolumeSerialNumber` field of this metadata. [Read more](../os/windows/fs/trait.metadataext#tymethod.volume_serial_number) [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#495-497)#### fn number\_of\_links(&self) -> Option<u32> 🔬This is a nightly-only experimental API. (`windows_by_handle` [#63010](https://github.com/rust-lang/rust/issues/63010)) Returns the value of the `nNumberOfLinks` field of this metadata. [Read more](../os/windows/fs/trait.metadataext#tymethod.number_of_links) [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#498-500)#### fn file\_index(&self) -> Option<u64> 🔬This is a nightly-only experimental API. (`windows_by_handle` [#63010](https://github.com/rust-lang/rust/issues/63010)) Returns the value of the `nFileIndex{Low,High}` fields of this metadata. [Read more](../os/windows/fs/trait.metadataext#tymethod.file_index) Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for Metadata ### impl Send for Metadata ### impl Sync for Metadata ### impl Unpin for Metadata ### impl UnwindSafe for Metadata Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::fs::OpenOptions Struct std::fs::OpenOptions =========================== ``` pub struct OpenOptions(_); ``` Options and flags which can be used to configure how a file is opened. This builder exposes the ability to configure how a [`File`](struct.file "File") is opened and what operations are permitted on the open file. The [`File::open`](struct.file#method.open "File::open") and [`File::create`](struct.file#method.create "File::create") methods are aliases for commonly used options using this builder. Generally speaking, when using `OpenOptions`, you’ll first call [`OpenOptions::new`](struct.openoptions#method.new "OpenOptions::new"), then chain calls to methods to set each option, then call [`OpenOptions::open`](struct.openoptions#method.open "OpenOptions::open"), passing the path of the file you’re trying to open. This will give you a [`io::Result`](../io/type.result "io::Result") with a [`File`](struct.file "File") inside that you can further operate on. Examples -------- Opening a file to read: ``` use std::fs::OpenOptions; let file = OpenOptions::new().read(true).open("foo.txt"); ``` Opening a file for both reading and writing, as well as creating it if it doesn’t exist: ``` use std::fs::OpenOptions; let file = OpenOptions::new() .read(true) .write(true) .create(true) .open("foo.txt"); ``` Implementations --------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#838-1062)### impl OpenOptions [source](https://doc.rust-lang.org/src/std/fs.rs.html#853-855)#### pub fn new() -> Self Creates a blank new set of options ready for configuration. All options are initially set to `false`. ##### Examples ``` use std::fs::OpenOptions; let mut options = OpenOptions::new(); let file = options.read(true).open("foo.txt"); ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#870-873)#### pub fn read(&mut self, read: bool) -> &mut Self Sets the option for read access. This option, when true, will indicate that the file should be `read`-able if opened. ##### Examples ``` use std::fs::OpenOptions; let file = OpenOptions::new().read(true).open("foo.txt"); ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#891-894)#### pub fn write(&mut self, write: bool) -> &mut Self Sets the option for write access. This option, when true, will indicate that the file should be `write`-able if opened. If the file already exists, any write calls on it will overwrite its contents, without truncating it. ##### Examples ``` use std::fs::OpenOptions; let file = OpenOptions::new().write(true).open("foo.txt"); ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#936-939)#### pub fn append(&mut self, append: bool) -> &mut Self Sets the option for the append mode. This option, when true, means that writes will append to a file instead of overwriting previous contents. Note that setting `.write(true).append(true)` has the same effect as setting only `.append(true)`. For most filesystems, the operating system guarantees that all writes are atomic: no writes get mangled because another process writes at the same time. One maybe obvious note when using append-mode: make sure that all data that belongs together is written to the file in one operation. This can be done by concatenating strings before passing them to [`write()`](../io/trait.write#tymethod.write "io::Write::write"), or using a buffered writer (with a buffer of adequate size), and calling [`flush()`](../io/trait.write#tymethod.flush "io::Write::flush") when the message is complete. If a file is opened with both read and append access, beware that after opening, and after every write, the position for reading may be set at the end of the file. So, before writing, save the current position (using `[seek](../io/trait.seek#tymethod.seek "io::Seek::seek")([SeekFrom](../io/enum.seekfrom "SeekFrom")::[Current](../io/enum.seekfrom#variant.Current "io::SeekFrom::Current")(0))`), and restore it before the next read. ###### [Note](#note) This function doesn’t create the file if it doesn’t exist. Use the [`OpenOptions::create`](struct.openoptions#method.create "OpenOptions::create") method to do so. ##### Examples ``` use std::fs::OpenOptions; let file = OpenOptions::new().append(true).open("foo.txt"); ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#956-959)#### pub fn truncate(&mut self, truncate: bool) -> &mut Self Sets the option for truncating a previous file. If a file is successfully opened with this option set it will truncate the file to 0 length if it already exists. The file must be opened with write access for truncate to work. ##### Examples ``` use std::fs::OpenOptions; let file = OpenOptions::new().write(true).truncate(true).open("foo.txt"); ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#974-977)#### pub fn create(&mut self, create: bool) -> &mut Self Sets the option to create a new file, or open it if it already exists. In order for the file to be created, [`OpenOptions::write`](struct.openoptions#method.write "OpenOptions::write") or [`OpenOptions::append`](struct.openoptions#method.append "OpenOptions::append") access must be used. ##### Examples ``` use std::fs::OpenOptions; let file = OpenOptions::new().write(true).create(true).open("foo.txt"); ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1007-1010)1.9.0 · #### pub fn create\_new(&mut self, create\_new: bool) -> &mut Self Sets the option to create a new file, failing if it already exists. No file is allowed to exist at the target location, also no (dangling) symlink. In this way, if the call succeeds, the file returned is guaranteed to be new. This option is useful because it is atomic. Otherwise between checking whether a file exists and creating a new one, the file may have been created by another process (a TOCTOU race condition / attack). If `.create_new(true)` is set, [`.create()`](struct.openoptions#method.create) and [`.truncate()`](struct.openoptions#method.truncate) are ignored. The file must be opened with write or append access in order to create a new file. ##### Examples ``` use std::fs::OpenOptions; let file = OpenOptions::new().write(true) .create_new(true) .open("foo.txt"); ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1055-1057)#### pub fn open<P: AsRef<Path>>(&self, path: P) -> Result<File> Opens a file at `path` with the options specified by `self`. ##### Errors This function will return an error under a number of different circumstances. Some of these error conditions are listed here, together with their [`io::ErrorKind`](../io/enum.errorkind "io::ErrorKind"). The mapping to [`io::ErrorKind`](../io/enum.errorkind "io::ErrorKind")s is not part of the compatibility contract of the function. * [`NotFound`](../io/enum.errorkind#variant.NotFound): The specified file does not exist and neither `create` or `create_new` is set. * [`NotFound`](../io/enum.errorkind#variant.NotFound): One of the directory components of the file path does not exist. * [`PermissionDenied`](../io/enum.errorkind#variant.PermissionDenied): The user lacks permission to get the specified access rights for the file. * [`PermissionDenied`](../io/enum.errorkind#variant.PermissionDenied): The user lacks permission to open one of the directory components of the specified path. * [`AlreadyExists`](../io/enum.errorkind#variant.AlreadyExists): `create_new` was specified and the file already exists. * [`InvalidInput`](../io/enum.errorkind#variant.InvalidInput): Invalid combinations of open options (truncate without write access, no access mode set, etc.). The following errors don’t match any existing [`io::ErrorKind`](../io/enum.errorkind "io::ErrorKind") at the moment: * One of the directory components of the specified file path was not, in fact, a directory. * Filesystem-level errors: full disk, write permission requested on a read-only file system, exceeded disk quota, too many open files, too long filename, too many symbolic links in the specified path (Unix-like systems only), etc. ##### Examples ``` use std::fs::OpenOptions; let file = OpenOptions::new().read(true).open("foo.txt"); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#183)### impl Clone for OpenOptions [source](https://doc.rust-lang.org/src/std/fs.rs.html#183)#### fn clone(&self) -> OpenOptions Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/fs.rs.html#183)### impl Debug for OpenOptions [source](https://doc.rust-lang.org/src/std/fs.rs.html#183)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#359-369)1.1.0 · ### impl OpenOptionsExt for OpenOptions Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#360-363)#### fn mode(&mut self, mode: u32) -> &mut OpenOptions Sets the mode bits that a new file will be created with. [Read more](../os/unix/fs/trait.openoptionsext#tymethod.mode) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#365-368)#### fn custom\_flags(&mut self, flags: i32) -> &mut OpenOptions Pass custom flags to the `flags` argument of `open`. [Read more](../os/unix/fs/trait.openoptionsext#tymethod.custom_flags) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#365-410)### impl OpenOptionsExt for OpenOptions Available on **WASI** only. [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#366-369)#### fn lookup\_flags(&mut self, flags: u32) -> &mut OpenOptions 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Pass custom `dirflags` argument to `path_open`. [Read more](../os/wasi/fs/trait.openoptionsext#tymethod.lookup_flags) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#371-374)#### fn directory(&mut self, dir: bool) -> &mut OpenOptions 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Indicates whether `OpenOptions` must open a directory or not. [Read more](../os/wasi/fs/trait.openoptionsext#tymethod.directory) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#376-379)#### fn dsync(&mut self, enabled: bool) -> &mut OpenOptions 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Indicates whether `__WASI_FDFLAG_DSYNC` is passed in the `fs_flags` field of `path_open`. [Read more](../os/wasi/fs/trait.openoptionsext#tymethod.dsync) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#381-384)#### fn nonblock(&mut self, enabled: bool) -> &mut OpenOptions 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Indicates whether `__WASI_FDFLAG_NONBLOCK` is passed in the `fs_flags` field of `path_open`. [Read more](../os/wasi/fs/trait.openoptionsext#tymethod.nonblock) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#386-389)#### fn rsync(&mut self, enabled: bool) -> &mut OpenOptions 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Indicates whether `__WASI_FDFLAG_RSYNC` is passed in the `fs_flags` field of `path_open`. [Read more](../os/wasi/fs/trait.openoptionsext#tymethod.rsync) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#391-394)#### fn sync(&mut self, enabled: bool) -> &mut OpenOptions 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Indicates whether `__WASI_FDFLAG_SYNC` is passed in the `fs_flags` field of `path_open`. [Read more](../os/wasi/fs/trait.openoptionsext#tymethod.sync) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#396-399)#### fn fs\_rights\_base(&mut self, rights: u64) -> &mut OpenOptions 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Indicates the value that should be passed in for the `fs_rights_base` parameter of `path_open`. [Read more](../os/wasi/fs/trait.openoptionsext#tymethod.fs_rights_base) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#401-404)#### fn fs\_rights\_inheriting(&mut self, rights: u64) -> &mut OpenOptions 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Indicates the value that should be passed in for the `fs_rights_inheriting` parameter of `path_open`. [Read more](../os/wasi/fs/trait.openoptionsext#tymethod.fs_rights_inheriting) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#406-409)#### fn open\_at<P: AsRef<Path>>(&self, file: &File, path: P) -> Result<File> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Open a file or directory. [Read more](../os/wasi/fs/trait.openoptionsext#tymethod.open_at) [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#268-293)1.10.0 · ### impl OpenOptionsExt for OpenOptions Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#269-272)#### fn access\_mode(&mut self, access: u32) -> &mut OpenOptions Overrides the `dwDesiredAccess` argument to the call to [`CreateFile`](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea) with the specified value. [Read more](../os/windows/fs/trait.openoptionsext#tymethod.access_mode) [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#274-277)#### fn share\_mode(&mut self, share: u32) -> &mut OpenOptions Overrides the `dwShareMode` argument to the call to [`CreateFile`](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea) with the specified value. [Read more](../os/windows/fs/trait.openoptionsext#tymethod.share_mode) [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#279-282)#### fn custom\_flags(&mut self, flags: u32) -> &mut OpenOptions Sets extra flags for the `dwFileFlags` argument to the call to [`CreateFile2`](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfile2) to the specified value (or combines it with `attributes` and `security_qos_flags` to set the `dwFlagsAndAttributes` for [`CreateFile`](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea)). [Read more](../os/windows/fs/trait.openoptionsext#tymethod.custom_flags) [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#284-287)#### fn attributes(&mut self, attributes: u32) -> &mut OpenOptions Sets the `dwFileAttributes` argument to the call to [`CreateFile2`](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfile2) to the specified value (or combines it with `custom_flags` and `security_qos_flags` to set the `dwFlagsAndAttributes` for [`CreateFile`](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea)). [Read more](../os/windows/fs/trait.openoptionsext#tymethod.attributes) [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#289-292)#### fn security\_qos\_flags(&mut self, flags: u32) -> &mut OpenOptions Sets the `dwSecurityQosFlags` argument to the call to [`CreateFile2`](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfile2) to the specified value (or combines it with `custom_flags` and `attributes` to set the `dwFlagsAndAttributes` for [`CreateFile`](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea)). [Read more](../os/windows/fs/trait.openoptionsext#tymethod.security_qos_flags) Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for OpenOptions ### impl Send for OpenOptions ### impl Sync for OpenOptions ### impl Unpin for OpenOptions ### impl UnwindSafe for OpenOptions Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Function std::fs::hard_link Function std::fs::hard\_link ============================ ``` pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(    original: P,    link: Q) -> Result<()> ``` Creates a new hard link on the filesystem. The `link` path will be a link pointing to the `original` path. Note that systems often require these two paths to both be located on the same filesystem. If `original` names a symbolic link, it is platform-specific whether the symbolic link is followed. On platforms where it’s possible to not follow it, it is not followed, and the created hard link points to the symbolic link itself. Platform-specific behavior -------------------------- This function currently corresponds the `CreateHardLink` function on Windows. On most Unix systems, it corresponds to the `linkat` function with no flags. On Android, VxWorks, and Redox, it instead corresponds to the `link` function. On MacOS, it uses the `linkat` function if it is available, but on very old systems where `linkat` is not available, `link` is selected at runtime instead. Note that, this [may change in the future](../io/index#platform-specific-behavior). Errors ------ This function will return an error in the following situations, but is not limited to just these cases: * The `original` path is not a file or doesn’t exist. Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt Ok(()) } ``` rust Function std::fs::create_dir_all Function std::fs::create\_dir\_all ================================== ``` pub fn create_dir_all<P: AsRef<Path>>(path: P) -> Result<()> ``` Recursively create a directory and all of its parent components if they are missing. Platform-specific behavior -------------------------- This function currently corresponds to the `mkdir` function on Unix and the `CreateDirectory` function on Windows. Note that, this [may change in the future](../io/index#platform-specific-behavior). Errors ------ This function will return an error in the following situations, but is not limited to just these cases: * If any directory in the path specified by `path` does not already exist and it could not be created otherwise. The specific error conditions for when a directory is being created (after it is determined to not exist) are outlined by [`fs::create_dir`](fn.create_dir). Notable exception is made for situations where any of the directories specified in the `path` could not be created as it was being created concurrently. Such cases are considered to be successful. That is, calling `create_dir_all` concurrently from multiple threads or processes is guaranteed not to fail due to a race condition with itself. Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { fs::create_dir_all("/some/dir")?; Ok(()) } ``` rust Function std::fs::read_to_string Function std::fs::read\_to\_string ================================== ``` pub fn read_to_string<P: AsRef<Path>>(path: P) -> Result<String> ``` Read the entire contents of a file into a string. This is a convenience function for using [`File::open`](struct.file#method.open "File::open") and [`read_to_string`](../io/trait.read#method.read_to_string) with fewer imports and without an intermediate variable. Errors ------ This function will return an error if `path` does not already exist. Other errors may also be returned according to [`OpenOptions::open`](struct.openoptions#method.open "OpenOptions::open"). It will also return an error if it encounters while reading an error of a kind other than [`io::ErrorKind::Interrupted`](../io/enum.errorkind#variant.Interrupted "io::ErrorKind::Interrupted"), or if the contents of the file are not valid UTF-8. Examples -------- ``` use std::fs; use std::net::SocketAddr; use std::error::Error; fn main() -> Result<(), Box<dyn Error>> { let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?; Ok(()) } ``` rust Function std::fs::symlink_metadata Function std::fs::symlink\_metadata =================================== ``` pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> Result<Metadata> ``` Query the metadata about a file without following symlinks. Platform-specific behavior -------------------------- This function currently corresponds to the `lstat` function on Unix and the `GetFileInformationByHandle` function on Windows. Note that, this [may change in the future](../io/index#platform-specific-behavior). Errors ------ This function will return an error in the following situations, but is not limited to just these cases: * The user lacks permissions to perform `metadata` call on `path`. * `path` does not exist. Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { let attr = fs::symlink_metadata("/some/file/path.txt")?; // inspect attr ... Ok(()) } ``` rust Function std::fs::canonicalize Function std::fs::canonicalize ============================== ``` pub fn canonicalize<P: AsRef<Path>>(path: P) -> Result<PathBuf> ``` Returns the canonical, absolute form of a path with all intermediate components normalized and symbolic links resolved. Platform-specific behavior -------------------------- This function currently corresponds to the `realpath` function on Unix and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows. Note that, this [may change in the future](../io/index#platform-specific-behavior). On Windows, this converts the path to use [extended length path](https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file) syntax, which allows your program to use longer path names, but means you can only join backslash-delimited paths to it, and it may be incompatible with other applications (if passed to the application on the command-line, or written to a file another application may read). Errors ------ This function will return an error in the following situations, but is not limited to just these cases: * `path` does not exist. * A non-final component in path is not a directory. Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { let path = fs::canonicalize("../a/../foo.txt")?; Ok(()) } ``` rust Function std::fs::set_permissions Function std::fs::set\_permissions ================================== ``` pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> Result<()> ``` Changes the permissions found on a file or a directory. Platform-specific behavior -------------------------- This function currently corresponds to the `chmod` function on Unix and the `SetFileAttributes` function on Windows. Note that, this [may change in the future](../io/index#platform-specific-behavior). Errors ------ This function will return an error in the following situations, but is not limited to just these cases: * `path` does not exist. * The user lacks the permission to change attributes of the file. Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { let mut perms = fs::metadata("foo.txt")?.permissions(); perms.set_readonly(true); fs::set_permissions("foo.txt", perms)?; Ok(()) } ``` rust Struct std::fs::DirBuilder Struct std::fs::DirBuilder ========================== ``` pub struct DirBuilder { /* private fields */ } ``` A builder used to create directories in various manners. This builder also supports platform-specific options. Implementations --------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#2329-2419)### impl DirBuilder [source](https://doc.rust-lang.org/src/std/fs.rs.html#2342-2344)#### pub fn new() -> DirBuilder Creates a new set of options with default mode/security settings for all platforms and also non-recursive. ##### Examples ``` use std::fs::DirBuilder; let builder = DirBuilder::new(); ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#2361-2364)#### pub fn recursive(&mut self, recursive: bool) -> &mut Self Indicates that directories should be created recursively, creating all parent directories. Parents that do not exist are created with the same security and permissions settings. This option defaults to `false`. ##### Examples ``` use std::fs::DirBuilder; let mut builder = DirBuilder::new(); builder.recursive(true); ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#2385-2387)#### pub fn create<P: AsRef<Path>>(&self, path: P) -> Result<()> Creates the specified directory with the options configured in this builder. It is considered an error if the directory already exists unless recursive mode is enabled. ##### Examples ``` use std::fs::{self, DirBuilder}; let path = "/tmp/foo/bar/baz"; DirBuilder::new() .recursive(true) .create(path).unwrap(); assert!(fs::metadata(path).unwrap().is_dir()); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#216)### impl Debug for DirBuilder [source](https://doc.rust-lang.org/src/std/fs.rs.html#216)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#923-928)### impl DirBuilderExt for DirBuilder Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#924-927)#### fn mode(&mut self, mode: u32) -> &mut DirBuilder Sets the mode to create new directories with. This option defaults to 0o777. [Read more](../os/unix/fs/trait.dirbuilderext#tymethod.mode) Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for DirBuilder ### impl Send for DirBuilder ### impl Sync for DirBuilder ### impl Unpin for DirBuilder ### impl UnwindSafe for DirBuilder Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Function std::fs::try_exists Function std::fs::try\_exists ============================= ``` pub fn try_exists<P: AsRef<Path>>(path: P) -> Result<bool> ``` 🔬This is a nightly-only experimental API. (`fs_try_exists` [#83186](https://github.com/rust-lang/rust/issues/83186)) Returns `Ok(true)` if the path points at an existing entity. This function will traverse symbolic links to query information about the destination file. In case of broken symbolic links this will return `Ok(false)`. As opposed to the [`Path::exists`](../path/struct.path#method.exists) method, this one doesn’t silently ignore errors unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission denied on some of the parent directories.) Note that while this avoids some pitfalls of the `exists()` method, it still can not prevent time-of-check to time-of-use (TOCTOU) bugs. You should only use it in scenarios where those bugs are not an issue. Examples -------- ``` #![feature(fs_try_exists)] use std::fs; assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt")); assert!(fs::try_exists("/root/secret_file.txt").is_err()); ``` rust Function std::fs::metadata Function std::fs::metadata ========================== ``` pub fn metadata<P: AsRef<Path>>(path: P) -> Result<Metadata> ``` Given a path, query the file system to get information about a file, directory, etc. This function will traverse symbolic links to query information about the destination file. Platform-specific behavior -------------------------- This function currently corresponds to the `stat` function on Unix and the `GetFileInformationByHandle` function on Windows. Note that, this [may change in the future](../io/index#platform-specific-behavior). Errors ------ This function will return an error in the following situations, but is not limited to just these cases: * The user lacks permissions to perform `metadata` call on `path`. * `path` does not exist. Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { let attr = fs::metadata("/some/file/path.txt")?; // inspect attr ... Ok(()) } ``` rust Struct std::fs::FileTimes Struct std::fs::FileTimes ========================= ``` pub struct FileTimes(_); ``` 🔬This is a nightly-only experimental API. (`file_set_times` [#98245](https://github.com/rust-lang/rust/issues/98245)) Representation of the various timestamps on a file. Implementations --------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#1341-1363)### impl FileTimes [source](https://doc.rust-lang.org/src/std/fs.rs.html#1346-1348)#### pub fn new() -> Self 🔬This is a nightly-only experimental API. (`file_set_times` [#98245](https://github.com/rust-lang/rust/issues/98245)) Create a new `FileTimes` with no times set. Using the resulting `FileTimes` in [`File::set_times`](struct.file#method.set_times "File::set_times") will not modify any timestamps. [source](https://doc.rust-lang.org/src/std/fs.rs.html#1352-1355)#### pub fn set\_accessed(self, t: SystemTime) -> Self 🔬This is a nightly-only experimental API. (`file_set_times` [#98245](https://github.com/rust-lang/rust/issues/98245)) Set the last access time of a file. [source](https://doc.rust-lang.org/src/std/fs.rs.html#1359-1362)#### pub fn set\_modified(self, t: SystemTime) -> Self 🔬This is a nightly-only experimental API. (`file_set_times` [#98245](https://github.com/rust-lang/rust/issues/98245)) Set the last modified time of a file. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#188)### impl Clone for FileTimes [source](https://doc.rust-lang.org/src/std/fs.rs.html#188)#### fn clone(&self) -> FileTimes Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/fs.rs.html#188)### impl Debug for FileTimes [source](https://doc.rust-lang.org/src/std/fs.rs.html#188)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/fs.rs.html#188)### impl Default for FileTimes [source](https://doc.rust-lang.org/src/std/fs.rs.html#188)#### fn default() -> FileTimes Returns the “default value” for a type. [Read more](../default/trait.default#tymethod.default) [source](https://doc.rust-lang.org/src/std/fs.rs.html#188)### impl Copy for FileTimes Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for FileTimes ### impl Send for FileTimes ### impl Sync for FileTimes ### impl Unpin for FileTimes ### impl UnwindSafe for FileTimes Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Function std::fs::write Function std::fs::write ======================= ``` pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> ``` Write a slice as the entire contents of a file. This function will create a file if it does not exist, and will entirely replace its contents if it does. Depending on the platform, this function may fail if the full directory path does not exist. This is a convenience function for using [`File::create`](struct.file#method.create "File::create") and [`write_all`](../io/trait.write#method.write_all) with fewer imports. Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { fs::write("foo.txt", b"Lorem ipsum")?; fs::write("bar.txt", "dolor sit")?; Ok(()) } ``` rust Function std::fs::create_dir Function std::fs::create\_dir ============================= ``` pub fn create_dir<P: AsRef<Path>>(path: P) -> Result<()> ``` Creates a new, empty directory at the provided path Platform-specific behavior -------------------------- This function currently corresponds to the `mkdir` function on Unix and the `CreateDirectory` function on Windows. Note that, this [may change in the future](../io/index#platform-specific-behavior). **NOTE**: If a parent of the given path doesn’t exist, this function will return an error. To create a directory and all its missing parents at the same time, use the [`create_dir_all`](fn.create_dir_all "create_dir_all") function. Errors ------ This function will return an error in the following situations, but is not limited to just these cases: * User lacks permissions to create directory at `path`. * A parent of the given path doesn’t exist. (To create a directory and all its missing parents at the same time, use the [`create_dir_all`](fn.create_dir_all "create_dir_all") function.) * `path` already exists. Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { fs::create_dir("/some/dir")?; Ok(()) } ``` rust Function std::fs::read_dir Function std::fs::read\_dir =========================== ``` pub fn read_dir<P: AsRef<Path>>(path: P) -> Result<ReadDir> ``` Returns an iterator over the entries within a directory. The iterator will yield instances of `[io::Result](../io/type.result "io::Result")<[DirEntry](struct.direntry "DirEntry")>`. New errors may be encountered after an iterator is initially constructed. Entries for the current and parent directories (typically `.` and `..`) are skipped. Platform-specific behavior -------------------------- This function currently corresponds to the `opendir` function on Unix and the `FindFirstFile` function on Windows. Advancing the iterator currently corresponds to `readdir` on Unix and `FindNextFile` on Windows. Note that, this [may change in the future](../io/index#platform-specific-behavior). The order in which this iterator returns entries is platform and filesystem dependent. Errors ------ This function will return an error in the following situations, but is not limited to just these cases: * The provided `path` doesn’t exist. * The process lacks permissions to view the contents. * The `path` points at a non-directory file. Examples -------- ``` use std::io; use std::fs::{self, DirEntry}; use std::path::Path; // one possible implementation of walking a directory only visiting files fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> { if dir.is_dir() { for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() { visit_dirs(&path, cb)?; } else { cb(&entry); } } } Ok(()) } ``` ``` use std::{fs, io}; fn main() -> io::Result<()> { let mut entries = fs::read_dir(".")? .map(|res| res.map(|e| e.path())) .collect::<Result<Vec<_>, io::Error>>()?; // The order in which `read_dir` returns entries is not guaranteed. If reproducible // ordering is required the entries should be explicitly sorted. entries.sort(); // The entries have now been sorted by their path. Ok(()) } ``` rust Struct std::fs::ReadDir Struct std::fs::ReadDir ======================= ``` pub struct ReadDir(_); ``` Iterator over the entries in a directory. This iterator is returned from the [`read_dir`](fn.read_dir "read_dir") function of this module and will yield instances of `[io::Result](../io/type.result "io::Result")<[DirEntry](struct.direntry "DirEntry")>`. Through a [`DirEntry`](struct.direntry "DirEntry") information like the entry’s path and possibly other metadata can be learned. The order in which this iterator returns entries is platform and filesystem dependent. Errors ------ This [`io::Result`](../io/type.result "io::Result") will be an [`Err`](../result/enum.result#variant.Err "Err") if there’s some sort of intermittent IO error during iteration. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#127)### impl Debug for ReadDir [source](https://doc.rust-lang.org/src/std/fs.rs.html#127)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/fs.rs.html#1539-1545)### impl Iterator for ReadDir #### type Item = Result<DirEntry, Error> The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/std/fs.rs.html#1542-1544)#### fn next(&mut self) -> Option<Result<DirEntry>> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#215)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for ReadDir ### impl Send for ReadDir ### impl Sync for ReadDir ### impl Unpin for ReadDir ### impl UnwindSafe for ReadDir Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::fs::DirEntry Struct std::fs::DirEntry ======================== ``` pub struct DirEntry(_); ``` Entries returned by the [`ReadDir`](struct.readdir "ReadDir") iterator. An instance of `DirEntry` represents an entry inside of a directory on the filesystem. Each entry can be inspected via methods to learn about the full path or possibly other metadata through per-platform extension traits. Platform-specific behavior -------------------------- On Unix, the `DirEntry` struct contains an internal reference to the open directory. Holding `DirEntry` objects will consume a file handle even after the `ReadDir` iterator is dropped. Note that this [may change in the future](../io/index#platform-specific-behavior). Implementations --------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#1547-1677)### impl DirEntry [source](https://doc.rust-lang.org/src/std/fs.rs.html#1578-1580)#### pub fn path(&self) -> PathBuf Returns the full path to the file that this entry represents. The full path is created by joining the original path to `read_dir` with the filename of this entry. ##### Examples ``` use std::fs; fn main() -> std::io::Result<()> { for entry in fs::read_dir(".")? { let dir = entry?; println!("{:?}", dir.path()); } Ok(()) } ``` This prints output like: ``` "./whatever.txt" "./foo.html" "./hello_world.rs" ``` The exact text, of course, depends on what files you have in `.`. [source](https://doc.rust-lang.org/src/std/fs.rs.html#1616-1618)1.1.0 · #### pub fn metadata(&self) -> Result<Metadata> Returns the metadata for the file that this entry points at. This function will not traverse symlinks if this entry points at a symlink. To traverse symlinks use [`fs::metadata`](fn.metadata) or [`fs::File::metadata`](struct.file#method.metadata). ##### Platform-specific behavior On Windows this function is cheap to call (no extra system calls needed), but on Unix platforms this function is the equivalent of calling `symlink_metadata` on the path. ##### Examples ``` use std::fs; if let Ok(entries) = fs::read_dir(".") { for entry in entries { if let Ok(entry) = entry { // Here, `entry` is a `DirEntry`. if let Ok(metadata) = entry.metadata() { // Now let's show our entry's permissions! println!("{:?}: {:?}", entry.path(), metadata.permissions()); } else { println!("Couldn't get metadata for {:?}", entry.path()); } } } } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1651-1653)1.1.0 · #### pub fn file\_type(&self) -> Result<FileType> Returns the file type for the file that this entry points at. This function will not traverse symlinks if this entry points at a symlink. ##### Platform-specific behavior On Windows and most Unix platforms this function is free (no extra system calls needed), but some Unix platforms may require the equivalent call to `symlink_metadata` to learn about the target file type. ##### Examples ``` use std::fs; if let Ok(entries) = fs::read_dir(".") { for entry in entries { if let Ok(entry) = entry { // Here, `entry` is a `DirEntry`. if let Ok(file_type) = entry.file_type() { // Now let's show our entry's file type! println!("{:?}: {:?}", entry.path(), file_type); } else { println!("Couldn't get file type for {:?}", entry.path()); } } } } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1674-1676)1.1.0 · #### pub fn file\_name(&self) -> OsString Returns the bare file name of this directory entry without any other leading path component. ##### Examples ``` use std::fs; if let Ok(entries) = fs::read_dir(".") { for entry in entries { if let Ok(entry) = entry { // Here, `entry` is a `DirEntry`. println!("{:?}", entry.file_name()); } } } ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#1680-1684)1.13.0 · ### impl Debug for DirEntry [source](https://doc.rust-lang.org/src/std/fs.rs.html#1681-1683)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#841-845)1.1.0 · ### impl DirEntryExt for DirEntry Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#842-844)#### fn ino(&self) -> u64 Returns the underlying `d_ino` field in the contained `dirent` structure. [Read more](../os/unix/fs/trait.direntryext#tymethod.ino) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#494-498)### impl DirEntryExt for DirEntry Available on **WASI** only. [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#495-497)#### fn ino(&self) -> u64 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Returns the underlying `d_ino` field of the `dirent_t` [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#878-882)### impl DirEntryExt2 for DirEntry Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#879-881)#### fn file\_name\_ref(&self) -> &OsStr 🔬This is a nightly-only experimental API. (`dir_entry_ext2` [#85573](https://github.com/rust-lang/rust/issues/85573)) Returns a reference to the underlying `OsStr` of this entry’s filename. [Read more](../os/unix/fs/trait.direntryext2#tymethod.file_name_ref) Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for DirEntry ### impl Send for DirEntry ### impl Sync for DirEntry ### impl Unpin for DirEntry ### impl UnwindSafe for DirEntry Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Function std::fs::remove_dir_all Function std::fs::remove\_dir\_all ================================== ``` pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> Result<()> ``` Removes a directory at this path, after removing all its contents. Use carefully! This function does **not** follow symbolic links and it will simply remove the symbolic link itself. Platform-specific behavior -------------------------- This function currently corresponds to `openat`, `fdopendir`, `unlinkat` and `lstat` functions on Unix (except for macOS before version 10.10 and REDOX) and the `CreateFileW`, `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile` functions on Windows. Note that, this [may change in the future](../io/index#platform-specific-behavior). On macOS before version 10.10 and REDOX, as well as when running in Miri for any target, this function is not protected against time-of-check to time-of-use (TOCTOU) race conditions, and should not be used in security-sensitive code on those platforms. All other platforms are protected. Errors ------ See [`fs::remove_file`](fn.remove_file) and [`fs::remove_dir`](fn.remove_dir). Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { fs::remove_dir_all("/some/dir")?; Ok(()) } ``` rust Struct std::fs::FileType Struct std::fs::FileType ======================== ``` pub struct FileType(_); ``` A structure representing a type of file with accessors for each file type. It is returned by [`Metadata::file_type`](struct.metadata#method.file_type "Metadata::file_type") method. Implementations --------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#1422-1518)### impl FileType [source](https://doc.rust-lang.org/src/std/fs.rs.html#1446-1448)#### pub fn is\_dir(&self) -> bool Tests whether this file type represents a directory. The result is mutually exclusive to the results of [`is_file`](struct.filetype#method.is_file) and [`is_symlink`](struct.filetype#method.is_symlink); only zero or one of these tests may pass. ##### Examples ``` fn main() -> std::io::Result<()> { use std::fs; let metadata = fs::metadata("foo.txt")?; let file_type = metadata.file_type(); assert_eq!(file_type.is_dir(), false); Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1479-1481)#### pub fn is\_file(&self) -> bool Tests whether this file type represents a regular file. The result is mutually exclusive to the results of [`is_dir`](struct.filetype#method.is_dir) and [`is_symlink`](struct.filetype#method.is_symlink); only zero or one of these tests may pass. When the goal is simply to read from (or write to) the source, the most reliable way to test the source can be read (or written to) is to open it. Only using `is_file` can break workflows like `diff <( prog_a )` on a Unix-like system for example. See [`File::open`](struct.file#method.open "File::open") or [`OpenOptions::open`](struct.openoptions#method.open "OpenOptions::open") for more information. ##### Examples ``` fn main() -> std::io::Result<()> { use std::fs; let metadata = fs::metadata("foo.txt")?; let file_type = metadata.file_type(); assert_eq!(file_type.is_file(), true); Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#1515-1517)#### pub fn is\_symlink(&self) -> bool Tests whether this file type represents a symbolic link. The result is mutually exclusive to the results of [`is_dir`](struct.filetype#method.is_dir) and [`is_file`](struct.filetype#method.is_file); only zero or one of these tests may pass. The underlying [`Metadata`](struct.metadata "Metadata") struct needs to be retrieved with the [`fs::symlink_metadata`](fn.symlink_metadata) function and not the [`fs::metadata`](fn.metadata) function. The [`fs::metadata`](fn.metadata) function follows symbolic links, so [`is_symlink`](struct.filetype#method.is_symlink) would always return `false` for the target file. ##### Examples ``` use std::fs; fn main() -> std::io::Result<()> { let metadata = fs::symlink_metadata("foo.txt")?; let file_type = metadata.file_type(); assert_eq!(file_type.is_symlink(), false); Ok(()) } ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#207)### impl Clone for FileType [source](https://doc.rust-lang.org/src/std/fs.rs.html#207)#### fn clone(&self) -> FileType Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/fs.rs.html#207)### impl Debug for FileType [source](https://doc.rust-lang.org/src/std/fs.rs.html#207)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#800-813)1.5.0 · ### impl FileTypeExt for FileType Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#801-803)#### fn is\_block\_device(&self) -> bool Returns `true` if this file type is a block device. [Read more](../os/unix/fs/trait.filetypeext#tymethod.is_block_device) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#804-806)#### fn is\_char\_device(&self) -> bool Returns `true` if this file type is a char device. [Read more](../os/unix/fs/trait.filetypeext#tymethod.is_char_device) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#807-809)#### fn is\_fifo(&self) -> bool Returns `true` if this file type is a fifo. [Read more](../os/unix/fs/trait.filetypeext#tymethod.is_fifo) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#810-812)#### fn is\_socket(&self) -> bool Returns `true` if this file type is a socket. [Read more](../os/unix/fs/trait.filetypeext#tymethod.is_socket) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#473-486)### impl FileTypeExt for FileType Available on **WASI** only. [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#474-476)#### fn is\_block\_device(&self) -> bool 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Returns `true` if this file type is a block device. [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#477-479)#### fn is\_char\_device(&self) -> bool 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Returns `true` if this file type is a character device. [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#480-482)#### fn is\_socket\_dgram(&self) -> bool 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Returns `true` if this file type is a socket datagram. [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#483-485)#### fn is\_socket\_stream(&self) -> bool 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Returns `true` if this file type is a socket stream. [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#468-470)#### fn is\_socket(&self) -> bool 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Returns `true` if this file type is any type of socket. [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#520-527)1.64.0 · ### impl FileTypeExt for FileType Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#521-523)#### fn is\_symlink\_dir(&self) -> bool Returns `true` if this file type is a symbolic link that is also a directory. [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#524-526)#### fn is\_symlink\_file(&self) -> bool Returns `true` if this file type is a symbolic link that is also a file. [source](https://doc.rust-lang.org/src/std/fs.rs.html#207)### impl Hash for FileType [source](https://doc.rust-lang.org/src/std/fs.rs.html#207)#### fn hash<\_\_H: Hasher>(&self, state: &mut \_\_H) Feeds this value into the given [`Hasher`](../hash/trait.hasher "Hasher"). [Read more](../hash/trait.hash#tymethod.hash) [source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0 · #### fn hash\_slice<H>(data: &[Self], state: &mut H)where H: [Hasher](../hash/trait.hasher "trait std::hash::Hasher"), Feeds a slice of this type into the given [`Hasher`](../hash/trait.hasher "Hasher"). [Read more](../hash/trait.hash#method.hash_slice) [source](https://doc.rust-lang.org/src/std/fs.rs.html#207)### impl PartialEq<FileType> for FileType [source](https://doc.rust-lang.org/src/std/fs.rs.html#207)#### fn eq(&self, other: &FileType) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)1.0.0 · #### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/std/fs.rs.html#207)### impl Copy for FileType [source](https://doc.rust-lang.org/src/std/fs.rs.html#207)### impl Eq for FileType [source](https://doc.rust-lang.org/src/std/fs.rs.html#207)### impl StructuralEq for FileType [source](https://doc.rust-lang.org/src/std/fs.rs.html#207)### impl StructuralPartialEq for FileType Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for FileType ### impl Send for FileType ### impl Sync for FileType ### impl Unpin for FileType ### impl UnwindSafe for FileType Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Function std::fs::copy Function std::fs::copy ====================== ``` pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<u64> ``` Copies the contents of one file to another. This function will also copy the permission bits of the original file to the destination file. This function will **overwrite** the contents of `to`. Note that if `from` and `to` both point to the same file, then the file will likely get truncated by this operation. On success, the total number of bytes copied is returned and it is equal to the length of the `to` file as reported by `metadata`. If you’re wanting to copy the contents of one file to another and you’re working with [`File`](struct.file "File")s, see the [`io::copy()`](../io/fn.copy "io::copy()") function. Platform-specific behavior -------------------------- This function currently corresponds to the `open` function in Unix with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`. `O_CLOEXEC` is set for returned file descriptors. On Linux (including Android), this function attempts to use `copy_file_range(2)`, and falls back to reading and writing if that is not possible. On Windows, this function currently corresponds to `CopyFileEx`. Alternate NTFS streams are copied but only the size of the main stream is returned by this function. On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`. Note that platform-specific behavior [may change in the future](../io/index#platform-specific-behavior). Errors ------ This function will return an error in the following situations, but is not limited to just these cases: * `from` is neither a regular file nor a symlink to a regular file. * `from` does not exist. * The current process does not have the permission rights to read `from` or write `to`. Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt Ok(()) } ``` rust Function std::fs::rename Function std::fs::rename ======================== ``` pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()> ``` Rename a file or directory to a new name, replacing the original file if `to` already exists. This will not work if the new name is on a different mount point. Platform-specific behavior -------------------------- This function currently corresponds to the `rename` function on Unix and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows. Because of this, the behavior when both `from` and `to` exist differs. On Unix, if `from` is a directory, `to` must also be an (empty) directory. If `from` is not a directory, `to` must also be not a directory. In contrast, on Windows, `from` can be anything, but `to` must *not* be a directory. Note that, this [may change in the future](../io/index#platform-specific-behavior). Errors ------ This function will return an error in the following situations, but is not limited to just these cases: * `from` does not exist. * The user lacks permissions to view contents. * `from` and `to` are on separate filesystems. Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt Ok(()) } ``` rust Function std::fs::remove_dir Function std::fs::remove\_dir ============================= ``` pub fn remove_dir<P: AsRef<Path>>(path: P) -> Result<()> ``` Removes an empty directory. Platform-specific behavior -------------------------- This function currently corresponds to the `rmdir` function on Unix and the `RemoveDirectory` function on Windows. Note that, this [may change in the future](../io/index#platform-specific-behavior). Errors ------ This function will return an error in the following situations, but is not limited to just these cases: * `path` doesn’t exist. * `path` isn’t a directory. * The user lacks permissions to remove the directory at the provided `path`. * The directory isn’t empty. Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { fs::remove_dir("/some/dir")?; Ok(()) } ``` rust Function std::fs::soft_link Function std::fs::soft\_link ============================ ``` pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(    original: P,    link: Q) -> Result<()> ``` 👎Deprecated since 1.1.0: replaced with std::os::unix::fs::symlink and std::os::windows::fs::{symlink\_file, symlink\_dir} Creates a new symbolic link on the filesystem. The `link` path will be a symbolic link pointing to the `original` path. On Windows, this will be a file symlink, not a directory symlink; for this reason, the platform-specific [`std::os::unix::fs::symlink`](../os/unix/fs/fn.symlink) and [`std::os::windows::fs::symlink_file`](../os/windows/fs/fn.symlink_file) or [`symlink_dir`](../os/windows/fs/fn.symlink_dir) should be used instead to make the intent explicit. Examples -------- ``` use std::fs; fn main() -> std::io::Result<()> { fs::soft_link("a.txt", "b.txt")?; Ok(()) } ``` rust Struct std::fs::File Struct std::fs::File ==================== ``` pub struct File { /* private fields */ } ``` An object providing access to an open file on the filesystem. An instance of a `File` can be read and/or written depending on what options it was opened with. Files also implement [`Seek`](../io/trait.seek "Seek") to alter the logical cursor that the file contains internally. Files are automatically closed when they go out of scope. Errors detected on closing are ignored by the implementation of `Drop`. Use the method [`sync_all`](struct.file#method.sync_all) if these errors must be manually handled. Examples -------- Creates a new file and write bytes to it (you can also use [`write()`](fn.write "write()")): ``` use std::fs::File; use std::io::prelude::*; fn main() -> std::io::Result<()> { let mut file = File::create("foo.txt")?; file.write_all(b"Hello, world!")?; Ok(()) } ``` Read the contents of a file into a [`String`](../string/struct.string "String") (you can also use [`read`](fn.read "read")): ``` use std::fs::File; use std::io::prelude::*; fn main() -> std::io::Result<()> { let mut file = File::open("foo.txt")?; let mut contents = String::new(); file.read_to_string(&mut contents)?; assert_eq!(contents, "Hello, world!"); Ok(()) } ``` It can be more efficient to read the contents of a file with a buffered [`Read`](../io/trait.read "Read")er. This can be accomplished with [`BufReader<R>`](../io/struct.bufreader): ``` use std::fs::File; use std::io::BufReader; use std::io::prelude::*; fn main() -> std::io::Result<()> { let file = File::open("foo.txt")?; let mut buf_reader = BufReader::new(file); let mut contents = String::new(); buf_reader.read_to_string(&mut contents)?; assert_eq!(contents, "Hello, world!"); Ok(()) } ``` Note that, although read and write methods require a `&mut File`, because of the interfaces for [`Read`](../io/trait.read "Read") and [`Write`](../io/trait.write "Write"), the holder of a `&File` can still modify the file, either through methods that take `&File` or by retrieving the underlying OS object and modifying the file that way. Additionally, many operating systems allow concurrent modification of files by different processes. Avoid assuming that holding a `&File` means that the file will not change. Platform-specific behavior -------------------------- On Windows, the implementation of [`Read`](../io/trait.read "Read") and [`Write`](../io/trait.write "Write") traits for `File` perform synchronous I/O operations. Therefore the underlying file must not have been opened for asynchronous I/O (e.g. by using `FILE_FLAG_OVERLAPPED`). Implementations --------------- [source](https://doc.rust-lang.org/src/std/fs.rs.html#330-685)### impl File [source](https://doc.rust-lang.org/src/std/fs.rs.html#351-353)#### pub fn open<P: AsRef<Path>>(path: P) -> Result<File> Attempts to open a file in read-only mode. See the [`OpenOptions::open`](struct.openoptions#method.open "OpenOptions::open") method for more details. ##### Errors This function will return an error if `path` does not already exist. Other errors may also be returned according to [`OpenOptions::open`](struct.openoptions#method.open "OpenOptions::open"). ##### Examples ``` use std::fs::File; fn main() -> std::io::Result<()> { let mut f = File::open("foo.txt")?; Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#376-378)#### pub fn create<P: AsRef<Path>>(path: P) -> Result<File> Opens a file in write-only mode. This function will create a file if it does not exist, and will truncate it if it does. Depending on the platform, this function may fail if the full directory path does not exist. See the [`OpenOptions::open`](struct.openoptions#method.open "OpenOptions::open") function for more details. ##### Examples ``` use std::fs::File; fn main() -> std::io::Result<()> { let mut f = File::create("foo.txt")?; Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#405-407)#### pub fn create\_new<P: AsRef<Path>>(path: P) -> Result<File> 🔬This is a nightly-only experimental API. (`file_create_new`) Creates a new file in read-write mode; error if the file exists. This function will create a file if it does not exist, or return an error if it does. This way, if the call succeeds, the file returned is guaranteed to be new. This option is useful because it is atomic. Otherwise between checking whether a file exists and creating a new one, the file may have been created by another process (a TOCTOU race condition / attack). This can also be written using `File::options().read(true).write(true).create_new(true).open(...)`. ##### Examples ``` #![feature(file_create_new)] use std::fs::File; fn main() -> std::io::Result<()> { let mut f = File::create_new("foo.txt")?; Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#435-437)1.58.0 · #### pub fn options() -> OpenOptions Returns a new OpenOptions object. This function returns a new OpenOptions object that you can use to open or create a file with specific options if `open()` or `create()` are not appropriate. It is equivalent to `OpenOptions::new()`, but allows you to write more readable code. Instead of `OpenOptions::new().append(true).open("example.log")`, you can write `File::options().append(true).open("example.log")`. This also avoids the need to import `OpenOptions`. See the [`OpenOptions::new`](struct.openoptions#method.new "OpenOptions::new") function for more details. ##### Examples ``` use std::fs::File; fn main() -> std::io::Result<()> { let mut f = File::options().append(true).open("example.log")?; Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#463-465)#### pub fn sync\_all(&self) -> Result<()> Attempts to sync all OS-internal metadata to disk. This function will attempt to ensure that all in-memory data reaches the filesystem before returning. This can be used to handle errors that would otherwise only be caught when the `File` is closed. Dropping a file will ignore errors in synchronizing this in-memory data. ##### Examples ``` use std::fs::File; use std::io::prelude::*; fn main() -> std::io::Result<()> { let mut f = File::create("foo.txt")?; f.write_all(b"Hello, world!")?; f.sync_all()?; Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#494-496)#### pub fn sync\_data(&self) -> Result<()> This function is similar to [`sync_all`](struct.file#method.sync_all), except that it might not synchronize file metadata to the filesystem. This is intended for use cases that must synchronize content, but don’t need the metadata on disk. The goal of this method is to reduce disk operations. Note that some platforms may simply implement this in terms of [`sync_all`](struct.file#method.sync_all). ##### Examples ``` use std::fs::File; use std::io::prelude::*; fn main() -> std::io::Result<()> { let mut f = File::create("foo.txt")?; f.write_all(b"Hello, world!")?; f.sync_data()?; Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#531-533)#### pub fn set\_len(&self, size: u64) -> Result<()> Truncates or extends the underlying file, updating the size of this file to become `size`. If the `size` is less than the current file’s size, then the file will be shrunk. If it is greater than the current file’s size, then the file will be extended to `size` and have all of the intermediate data filled in with 0s. The file’s cursor isn’t changed. In particular, if the cursor was at the end and the file is shrunk using this operation, the cursor will now be past the end. ##### Errors This function will return an error if the file is not opened for writing. Also, std::io::ErrorKind::InvalidInput will be returned if the desired length would cause an overflow due to the implementation specifics. ##### Examples ``` use std::fs::File; fn main() -> std::io::Result<()> { let mut f = File::create("foo.txt")?; f.set_len(10)?; Ok(()) } ``` Note that this method alters the content of the underlying file, even though it takes `&self` rather than `&mut self`. [source](https://doc.rust-lang.org/src/std/fs.rs.html#549-551)#### pub fn metadata(&self) -> Result<Metadata> Queries metadata about the underlying file. ##### Examples ``` use std::fs::File; fn main() -> std::io::Result<()> { let mut f = File::open("foo.txt")?; let metadata = f.metadata()?; Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#593-595)1.9.0 · #### pub fn try\_clone(&self) -> Result<File> Creates a new `File` instance that shares the same underlying file handle as the existing `File` instance. Reads, writes, and seeks will affect both `File` instances simultaneously. ##### Examples Creates two handles for a file named `foo.txt`: ``` use std::fs::File; fn main() -> std::io::Result<()> { let mut file = File::open("foo.txt")?; let file_copy = file.try_clone()?; Ok(()) } ``` Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create two handles, seek one of them, and read the remaining bytes from the other handle: ``` use std::fs::File; use std::io::SeekFrom; use std::io::prelude::*; fn main() -> std::io::Result<()> { let mut file = File::open("foo.txt")?; let mut file_copy = file.try_clone()?; file.seek(SeekFrom::Start(3))?; let mut contents = vec![]; file_copy.read_to_end(&mut contents)?; assert_eq!(contents, b"def\n"); Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#630-632)1.16.0 · #### pub fn set\_permissions(&self, perm: Permissions) -> Result<()> Changes the permissions on the underlying file. ##### Platform-specific behavior This function currently corresponds to the `fchmod` function on Unix and the `SetFileInformationByHandle` function on Windows. Note that, this [may change in the future](../io/index#platform-specific-behavior). ##### Errors This function will return an error if the user lacks permission change attributes on the underlying file. It may also return an error in other os-specific unspecified cases. ##### Examples ``` fn main() -> std::io::Result<()> { use std::fs::File; let file = File::open("foo.txt")?; let mut perms = file.metadata()?.permissions(); perms.set_readonly(true); file.set_permissions(perms)?; Ok(()) } ``` Note that this method alters the permissions of the underlying file, even though it takes `&self` rather than `&mut self`. [source](https://doc.rust-lang.org/src/std/fs.rs.html#673-675)#### pub fn set\_times(&self, times: FileTimes) -> Result<()> 🔬This is a nightly-only experimental API. (`file_set_times` [#98245](https://github.com/rust-lang/rust/issues/98245)) Changes the timestamps of the underlying file. ##### Platform-specific behavior This function currently corresponds to the `futimens` function on Unix (falling back to `futimes` on macOS before 10.13) and the `SetFileTime` function on Windows. Note that this [may change in the future](../io/index#platform-specific-behavior). ##### Errors This function will return an error if the user lacks permission to change timestamps on the underlying file. It may also return an error in other os-specific unspecified cases. This function may return an error if the operating system lacks support to change one or more of the timestamps set in the `FileTimes` structure. ##### Examples ``` #![feature(file_set_times)] fn main() -> std::io::Result<()> { use std::fs::{self, File, FileTimes}; let src = fs::metadata("src")?; let dest = File::options().write(true).open("dest")?; let times = FileTimes::new() .set_accessed(src.accessed()?) .set_modified(src.modified()?); dest.set_times(times)?; Ok(()) } ``` [source](https://doc.rust-lang.org/src/std/fs.rs.html#682-684)#### pub fn set\_modified(&self, time: SystemTime) -> Result<()> 🔬This is a nightly-only experimental API. (`file_set_times` [#98245](https://github.com/rust-lang/rust/issues/98245)) Changes the modification time of the underlying file. This is an alias for `set_times(FileTimes::new().set_modified(time))`. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#259-264)1.63.0 · ### impl AsFd for File [source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#261-263)#### fn as\_fd(&self) -> BorrowedFd<'\_> Available on **Unix** only.Borrows the file descriptor. [Read more](../os/unix/io/trait.asfd#tymethod.as_fd) [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#443-448)1.63.0 · ### impl AsHandle for File Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#445-447)#### fn as\_handle(&self) -> BorrowedHandle<'\_> Borrows the handle. [Read more](../os/windows/io/trait.ashandle#tymethod.as_handle) [source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#161-166)### impl AsRawFd for File [source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#163-165)#### fn as\_raw\_fd(&self) -> RawFd Available on **Unix** only.Extracts the raw file descriptor. [Read more](../os/unix/io/trait.asrawfd#tymethod.as_raw_fd) [source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#97-102)### impl AsRawHandle for File Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#99-101)#### fn as\_raw\_handle(&self) -> RawHandle Extracts the raw handle. [Read more](../os/windows/io/trait.asrawhandle#tymethod.as_raw_handle) [source](https://doc.rust-lang.org/src/std/fs.rs.html#710-714)### impl Debug for File [source](https://doc.rust-lang.org/src/std/fs.rs.html#711-713)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#217-224)1.15.0 · ### impl FileExt for File Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#218-220)#### fn read\_at(&self, buf: &mut [u8], offset: u64) -> Result<usize> Reads a number of bytes starting from a given offset. [Read more](../os/unix/fs/trait.fileext#tymethod.read_at) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#221-223)#### fn write\_at(&self, buf: &[u8], offset: u64) -> Result<usize> Writes a number of bytes starting from a given offset. [Read more](../os/unix/fs/trait.fileext#tymethod.write_at) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#103-121)1.33.0 · #### fn read\_exact\_at(&self, buf: &mut [u8], offset: u64) -> Result<()> Reads the exact number of byte required to fill `buf` from the given offset. [Read more](../os/unix/fs/trait.fileext#method.read_exact_at) [source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#195-213)1.33.0 · #### fn write\_all\_at(&self, buf: &[u8], offset: u64) -> Result<()> Attempts to write an entire buffer starting from a given offset. [Read more](../os/unix/fs/trait.fileext#method.write_all_at) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#231-295)### impl FileExt for File Available on **WASI** only. [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#232-234)#### fn read\_vectored\_at( &self, bufs: &mut [IoSliceMut<'\_>], offset: u64) -> Result<usize> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Reads a number of bytes starting from a given offset. [Read more](../os/wasi/fs/trait.fileext#tymethod.read_vectored_at) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#236-238)#### fn write\_vectored\_at(&self, bufs: &[IoSlice<'\_>], offset: u64) -> Result<usize> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Writes a number of bytes starting from a given offset. [Read more](../os/wasi/fs/trait.fileext#tymethod.write_vectored_at) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#240-242)#### fn tell(&self) -> Result<u64> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Returns the current position within the file. [Read more](../os/wasi/fs/trait.fileext#tymethod.tell) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#244-246)#### fn fdstat\_set\_flags(&self, flags: u16) -> Result<()> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Adjust the flags associated with this file. [Read more](../os/wasi/fs/trait.fileext#tymethod.fdstat_set_flags) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#248-250)#### fn fdstat\_set\_rights(&self, rights: u64, inheriting: u64) -> Result<()> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Adjust the rights associated with this file. [Read more](../os/wasi/fs/trait.fileext#tymethod.fdstat_set_rights) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#252-269)#### fn advise(&self, offset: u64, len: u64, advice: u8) -> Result<()> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Provide file advisory information on a file descriptor. [Read more](../os/wasi/fs/trait.fileext#tymethod.advise) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#271-273)#### fn allocate(&self, offset: u64, len: u64) -> Result<()> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Force the allocation of space in a file. [Read more](../os/wasi/fs/trait.fileext#tymethod.allocate) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#275-277)#### fn create\_directory<P: AsRef<Path>>(&self, dir: P) -> Result<()> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Create a directory. [Read more](../os/wasi/fs/trait.fileext#tymethod.create_directory) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#279-281)#### fn read\_link<P: AsRef<Path>>(&self, path: P) -> Result<PathBuf> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Read the contents of a symbolic link. [Read more](../os/wasi/fs/trait.fileext#tymethod.read_link) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#283-286)#### fn metadata\_at<P: AsRef<Path>>( &self, lookup\_flags: u32, path: P) -> Result<Metadata> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Return the attributes of a file or directory. [Read more](../os/wasi/fs/trait.fileext#tymethod.metadata_at) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#288-290)#### fn remove\_file<P: AsRef<Path>>(&self, path: P) -> Result<()> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Unlink a file. [Read more](../os/wasi/fs/trait.fileext#tymethod.remove_file) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#292-294)#### fn remove\_directory<P: AsRef<Path>>(&self, path: P) -> Result<()> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Remove a directory. [Read more](../os/wasi/fs/trait.fileext#tymethod.remove_directory) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#30-33)#### fn read\_at(&self, buf: &mut [u8], offset: u64) -> Result<usize> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Reads a number of bytes starting from a given offset. [Read more](../os/wasi/fs/trait.fileext#method.read_at) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#76-94)1.33.0 · #### fn read\_exact\_at(&self, buf: &mut [u8], offset: u64) -> Result<()> Reads the exact number of byte required to fill `buf` from the given offset. [Read more](../os/wasi/fs/trait.fileext#method.read_exact_at) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#110-113)#### fn write\_at(&self, buf: &[u8], offset: u64) -> Result<usize> 🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213)) Writes a number of bytes starting from a given offset. [Read more](../os/wasi/fs/trait.fileext#method.write_at) [source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#152-170)1.33.0 · #### fn write\_all\_at(&self, buf: &[u8], offset: u64) -> Result<()> Attempts to write an entire buffer starting from a given offset. [Read more](../os/wasi/fs/trait.fileext#method.write_all_at) [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#87-95)1.15.0 · ### impl FileExt for File Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#88-90)#### fn seek\_read(&self, buf: &mut [u8], offset: u64) -> Result<usize> Seeks to a given position and reads a number of bytes. [Read more](../os/windows/fs/trait.fileext#tymethod.seek_read) [source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#92-94)#### fn seek\_write(&self, buf: &[u8], offset: u64) -> Result<usize> Seeks to a given position and writes a number of bytes. [Read more](../os/windows/fs/trait.fileext#tymethod.seek_write) [source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#267-272)1.63.0 · ### impl From<File> for OwnedFd [source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#269-271)#### fn from(file: File) -> OwnedFd Converts to this type from the input type. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#451-456)1.63.0 · ### impl From<File> for OwnedHandle Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#453-455)#### fn from(file: File) -> OwnedHandle Converts to this type from the input type. [source](https://doc.rust-lang.org/src/std/process.rs.html#1397-1421)1.20.0 · ### impl From<File> for Stdio [source](https://doc.rust-lang.org/src/std/process.rs.html#1418-1420)#### fn from(file: File) -> Stdio Converts a [`File`](struct.file) into a [`Stdio`](../process/struct.stdio "Stdio"). ##### Examples `File` will be converted to `Stdio` using `Stdio::from` under the hood. ``` use std::fs::File; use std::process::Command; // With the `foo.txt` file containing `Hello, world!" let file = File::open("foo.txt").unwrap(); let reverse = Command::new("rev") .stdin(file) // Implicit File conversion into a Stdio .output() .expect("failed reverse command"); assert_eq!(reverse.stdout, b"!dlrow ,olleH"); ``` [source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#275-280)1.63.0 · ### impl From<OwnedFd> for File [source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#277-279)#### fn from(owned\_fd: OwnedFd) -> Self Converts to this type from the input type. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#459-464)1.63.0 · ### impl From<OwnedHandle> for File Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#461-463)#### fn from(owned: OwnedHandle) -> Self Converts to this type from the input type. [source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#168-173)1.1.0 · ### impl FromRawFd for File [source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#170-172)#### unsafe fn from\_raw\_fd(fd: RawFd) -> File Notable traits for [File](struct.file "struct std::fs::File") ``` impl Read for File impl Write for File impl Read for &File impl Write for &File ``` Available on **Unix** only.Constructs a new instance of `Self` from the given raw file descriptor. [Read more](../os/unix/io/trait.fromrawfd#tymethod.from_raw_fd) [source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#159-167)1.1.0 · ### impl FromRawHandle for File Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#161-166)#### unsafe fn from\_raw\_handle(handle: RawHandle) -> File Notable traits for [File](struct.file "struct std::fs::File") ``` impl Read for File impl Write for File impl Read for &File impl Write for &File ``` Constructs a new I/O object from the specified raw handle. [Read more](../os/windows/io/trait.fromrawhandle#tymethod.from_raw_handle) [source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#175-180)1.4.0 · ### impl IntoRawFd for File [source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#177-179)#### fn into\_raw\_fd(self) -> RawFd Available on **Unix** only.Consumes this object, returning the raw underlying file descriptor. [Read more](../os/unix/io/trait.intorawfd#tymethod.into_raw_fd) [source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#170-175)1.4.0 · ### impl IntoRawHandle for File Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#172-174)#### fn into\_raw\_handle(self) -> RawHandle Consumes this object, returning the raw underlying handle. [Read more](../os/windows/io/trait.intorawhandle#tymethod.into_raw_handle) [source](https://doc.rust-lang.org/src/std/fs.rs.html#782-811)### impl Read for &File [source](https://doc.rust-lang.org/src/std/fs.rs.html#783-785)#### fn read(&mut self, buf: &mut [u8]) -> Result<usize> Pull some bytes from this source into the specified buffer, returning how many bytes were read. [Read more](../io/trait.read#tymethod.read) [source](https://doc.rust-lang.org/src/std/fs.rs.html#787-789)#### fn read\_buf(&mut self, cursor: BorrowedCursor<'\_>) -> Result<()> 🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485)) Pull some bytes from this source into the specified buffer. [Read more](../io/trait.read#method.read_buf) [source](https://doc.rust-lang.org/src/std/fs.rs.html#791-793)#### fn read\_vectored(&mut self, bufs: &mut [IoSliceMut<'\_>]) -> Result<usize> Like `read`, except that it reads into a slice of buffers. [Read more](../io/trait.read#method.read_vectored) [source](https://doc.rust-lang.org/src/std/fs.rs.html#796-798)#### fn is\_read\_vectored(&self) -> bool 🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941)) Determines if this `Read`er has an efficient `read_vectored` implementation. [Read more](../io/trait.read#method.is_read_vectored) [source](https://doc.rust-lang.org/src/std/fs.rs.html#801-804)#### fn read\_to\_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> Read all bytes until EOF in this source, placing them into `buf`. [Read more](../io/trait.read#method.read_to_end) [source](https://doc.rust-lang.org/src/std/fs.rs.html#807-810)#### fn read\_to\_string(&mut self, buf: &mut String) -> Result<usize> Read all bytes until EOF in this source, appending them to `buf`. [Read more](../io/trait.read#method.read_to_string) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#804-806)1.6.0 · #### fn read\_exact(&mut self, buf: &mut [u8]) -> Result<()> Read the exact number of bytes required to fill `buf`. [Read more](../io/trait.read#method.read_exact) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#824-839)#### fn read\_buf\_exact(&mut self, cursor: BorrowedCursor<'\_>) -> Result<()> 🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485)) Read the exact number of bytes required to fill `cursor`. [Read more](../io/trait.read#method.read_buf_exact) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#876-881)#### fn by\_ref(&mut self) -> &mut Selfwhere Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Creates a “by reference” adaptor for this instance of `Read`. [Read more](../io/trait.read#method.by_ref) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#919-924)#### fn bytes(self) -> Bytes<Self>where Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Bytes](../io/struct.bytes "struct std::io::Bytes")<R> ``` impl<R: Read> Iterator for Bytes<R> type Item = Result<u8>; ``` Transforms this `Read` instance to an [`Iterator`](../iter/trait.iterator "Iterator") over its bytes. [Read more](../io/trait.read#method.bytes) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#957-962)#### fn chain<R: Read>(self, next: R) -> Chain<Self, R>where Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Chain](../io/struct.chain "struct std::io::Chain")<T, U> ``` impl<T: Read, U: Read> Read for Chain<T, U> ``` Creates an adapter which will chain this stream with another. [Read more](../io/trait.read#method.chain) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#996-1001)#### fn take(self, limit: u64) -> Take<Self>where Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Take](../io/struct.take "struct std::io::Take")<T> ``` impl<T: Read> Read for Take<T> ``` Creates an adapter which will read at most `limit` bytes from it. [Read more](../io/trait.read#method.take) [source](https://doc.rust-lang.org/src/std/fs.rs.html#726-755)### impl Read for File [source](https://doc.rust-lang.org/src/std/fs.rs.html#727-729)#### fn read(&mut self, buf: &mut [u8]) -> Result<usize> Pull some bytes from this source into the specified buffer, returning how many bytes were read. [Read more](../io/trait.read#tymethod.read) [source](https://doc.rust-lang.org/src/std/fs.rs.html#731-733)#### fn read\_vectored(&mut self, bufs: &mut [IoSliceMut<'\_>]) -> Result<usize> Like `read`, except that it reads into a slice of buffers. [Read more](../io/trait.read#method.read_vectored) [source](https://doc.rust-lang.org/src/std/fs.rs.html#735-737)#### fn read\_buf(&mut self, cursor: BorrowedCursor<'\_>) -> Result<()> 🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485)) Pull some bytes from this source into the specified buffer. [Read more](../io/trait.read#method.read_buf) [source](https://doc.rust-lang.org/src/std/fs.rs.html#740-742)#### fn is\_read\_vectored(&self) -> bool 🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941)) Determines if this `Read`er has an efficient `read_vectored` implementation. [Read more](../io/trait.read#method.is_read_vectored) [source](https://doc.rust-lang.org/src/std/fs.rs.html#745-748)#### fn read\_to\_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> Read all bytes until EOF in this source, placing them into `buf`. [Read more](../io/trait.read#method.read_to_end) [source](https://doc.rust-lang.org/src/std/fs.rs.html#751-754)#### fn read\_to\_string(&mut self, buf: &mut String) -> Result<usize> Read all bytes until EOF in this source, appending them to `buf`. [Read more](../io/trait.read#method.read_to_string) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#804-806)1.6.0 · #### fn read\_exact(&mut self, buf: &mut [u8]) -> Result<()> Read the exact number of bytes required to fill `buf`. [Read more](../io/trait.read#method.read_exact) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#824-839)#### fn read\_buf\_exact(&mut self, cursor: BorrowedCursor<'\_>) -> Result<()> 🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485)) Read the exact number of bytes required to fill `cursor`. [Read more](../io/trait.read#method.read_buf_exact) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#876-881)#### fn by\_ref(&mut self) -> &mut Selfwhere Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Creates a “by reference” adaptor for this instance of `Read`. [Read more](../io/trait.read#method.by_ref) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#919-924)#### fn bytes(self) -> Bytes<Self>where Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Bytes](../io/struct.bytes "struct std::io::Bytes")<R> ``` impl<R: Read> Iterator for Bytes<R> type Item = Result<u8>; ``` Transforms this `Read` instance to an [`Iterator`](../iter/trait.iterator "Iterator") over its bytes. [Read more](../io/trait.read#method.bytes) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#957-962)#### fn chain<R: Read>(self, next: R) -> Chain<Self, R>where Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Chain](../io/struct.chain "struct std::io::Chain")<T, U> ``` impl<T: Read, U: Read> Read for Chain<T, U> ``` Creates an adapter which will chain this stream with another. [Read more](../io/trait.read#method.chain) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#996-1001)#### fn take(self, limit: u64) -> Take<Self>where Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Take](../io/struct.take "struct std::io::Take")<T> ``` impl<T: Read> Read for Take<T> ``` Creates an adapter which will read at most `limit` bytes from it. [Read more](../io/trait.read#method.take) [source](https://doc.rust-lang.org/src/std/fs.rs.html#832-836)### impl Seek for &File [source](https://doc.rust-lang.org/src/std/fs.rs.html#833-835)#### fn seek(&mut self, pos: SeekFrom) -> Result<u64> Seek to an offset, in bytes, in a stream. [Read more](../io/trait.seek#tymethod.seek) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1796-1799)1.55.0 · #### fn rewind(&mut self) -> Result<()> Rewind to the beginning of a stream. [Read more](../io/trait.seek#method.rewind) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1836-1847)#### fn stream\_len(&mut self) -> Result<u64> 🔬This is a nightly-only experimental API. (`seek_stream_len` [#59359](https://github.com/rust-lang/rust/issues/59359)) Returns the length of this stream (in bytes). [Read more](../io/trait.seek#method.stream_len) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1873-1875)1.51.0 · #### fn stream\_position(&mut self) -> Result<u64> Returns the current seek position from the start of the stream. [Read more](../io/trait.seek#method.stream_position) [source](https://doc.rust-lang.org/src/std/fs.rs.html#776-780)### impl Seek for File [source](https://doc.rust-lang.org/src/std/fs.rs.html#777-779)#### fn seek(&mut self, pos: SeekFrom) -> Result<u64> Seek to an offset, in bytes, in a stream. [Read more](../io/trait.seek#tymethod.seek) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1796-1799)1.55.0 · #### fn rewind(&mut self) -> Result<()> Rewind to the beginning of a stream. [Read more](../io/trait.seek#method.rewind) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1836-1847)#### fn stream\_len(&mut self) -> Result<u64> 🔬This is a nightly-only experimental API. (`seek_stream_len` [#59359](https://github.com/rust-lang/rust/issues/59359)) Returns the length of this stream (in bytes). [Read more](../io/trait.seek#method.stream_len) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1873-1875)1.51.0 · #### fn stream\_position(&mut self) -> Result<u64> Returns the current seek position from the start of the stream. [Read more](../io/trait.seek#method.stream_position) [source](https://doc.rust-lang.org/src/std/fs.rs.html#813-830)### impl Write for &File [source](https://doc.rust-lang.org/src/std/fs.rs.html#814-816)#### fn write(&mut self, buf: &[u8]) -> Result<usize> Write a buffer into this writer, returning how many bytes were written. [Read more](../io/trait.write#tymethod.write) [source](https://doc.rust-lang.org/src/std/fs.rs.html#818-820)#### fn write\_vectored(&mut self, bufs: &[IoSlice<'\_>]) -> Result<usize> Like [`write`](../io/trait.write#tymethod.write), except that it writes from a slice of buffers. [Read more](../io/trait.write#method.write_vectored) [source](https://doc.rust-lang.org/src/std/fs.rs.html#823-825)#### fn is\_write\_vectored(&self) -> bool 🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941)) Determines if this `Write`r has an efficient [`write_vectored`](../io/trait.write#method.write_vectored) implementation. [Read more](../io/trait.write#method.is_write_vectored) [source](https://doc.rust-lang.org/src/std/fs.rs.html#827-829)#### fn flush(&mut self) -> Result<()> Flush this output stream, ensuring that all intermediately buffered contents reach their destination. [Read more](../io/trait.write#tymethod.flush) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1537-1552)#### fn write\_all(&mut self, buf: &[u8]) -> Result<()> Attempts to write an entire buffer into this writer. [Read more](../io/trait.write#method.write_all) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1602-1620)#### fn write\_all\_vectored(&mut self, bufs: &mut [IoSlice<'\_>]) -> Result<()> 🔬This is a nightly-only experimental API. (`write_all_vectored` [#70436](https://github.com/rust-lang/rust/issues/70436)) Attempts to write multiple buffers into this writer. [Read more](../io/trait.write#method.write_all_vectored) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1658-1690)#### fn write\_fmt(&mut self, fmt: Arguments<'\_>) -> Result<()> Writes a formatted string into this writer, returning any error encountered. [Read more](../io/trait.write#method.write_fmt) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1714-1719)#### fn by\_ref(&mut self) -> &mut Selfwhere Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Creates a “by reference” adapter for this instance of `Write`. [Read more](../io/trait.write#method.by_ref) [source](https://doc.rust-lang.org/src/std/fs.rs.html#757-774)### impl Write for File [source](https://doc.rust-lang.org/src/std/fs.rs.html#758-760)#### fn write(&mut self, buf: &[u8]) -> Result<usize> Write a buffer into this writer, returning how many bytes were written. [Read more](../io/trait.write#tymethod.write) [source](https://doc.rust-lang.org/src/std/fs.rs.html#762-764)#### fn write\_vectored(&mut self, bufs: &[IoSlice<'\_>]) -> Result<usize> Like [`write`](../io/trait.write#tymethod.write), except that it writes from a slice of buffers. [Read more](../io/trait.write#method.write_vectored) [source](https://doc.rust-lang.org/src/std/fs.rs.html#767-769)#### fn is\_write\_vectored(&self) -> bool 🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941)) Determines if this `Write`r has an efficient [`write_vectored`](../io/trait.write#method.write_vectored) implementation. [Read more](../io/trait.write#method.is_write_vectored) [source](https://doc.rust-lang.org/src/std/fs.rs.html#771-773)#### fn flush(&mut self) -> Result<()> Flush this output stream, ensuring that all intermediately buffered contents reach their destination. [Read more](../io/trait.write#tymethod.flush) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1537-1552)#### fn write\_all(&mut self, buf: &[u8]) -> Result<()> Attempts to write an entire buffer into this writer. [Read more](../io/trait.write#method.write_all) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1602-1620)#### fn write\_all\_vectored(&mut self, bufs: &mut [IoSlice<'\_>]) -> Result<()> 🔬This is a nightly-only experimental API. (`write_all_vectored` [#70436](https://github.com/rust-lang/rust/issues/70436)) Attempts to write multiple buffers into this writer. [Read more](../io/trait.write#method.write_all_vectored) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1658-1690)#### fn write\_fmt(&mut self, fmt: Arguments<'\_>) -> Result<()> Writes a formatted string into this writer, returning any error encountered. [Read more](../io/trait.write#method.write_fmt) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1714-1719)#### fn by\_ref(&mut self) -> &mut Selfwhere Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Creates a “by reference” adapter for this instance of `Write`. [Read more](../io/trait.write#method.by_ref) Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for File ### impl Send for File ### impl Sync for File ### impl Unpin for File ### impl UnwindSafe for File Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::thread::ThreadId Struct std::thread::ThreadId ============================ ``` pub struct ThreadId(_); ``` A unique identifier for a running thread. A `ThreadId` is an opaque object that uniquely identifies each thread created during the lifetime of a process. `ThreadId`s are guaranteed not to be reused, even when a thread terminates. `ThreadId`s are under the control of Rust’s standard library and there may not be any relationship between `ThreadId` and the underlying platform’s notion of a thread identifier – the two concepts cannot, therefore, be used interchangeably. A `ThreadId` can be retrieved from the [`id`](struct.thread#method.id) method on a [`Thread`](struct.thread "Thread"). Examples -------- ``` use std::thread; let other_thread = thread::spawn(|| { thread::current().id() }); let other_thread_id = other_thread.join().unwrap(); assert!(thread::current().id() != other_thread_id); ``` Implementations --------------- [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1042-1103)### impl ThreadId [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1100-1102)#### pub fn as\_u64(&self) -> NonZeroU64 🔬This is a nightly-only experimental API. (`thread_id_value` [#67939](https://github.com/rust-lang/rust/issues/67939)) This returns a numeric identifier for the thread identified by this `ThreadId`. As noted in the documentation for the type itself, it is essentially an opaque ID, but is guaranteed to be unique for each thread. The returned value is entirely opaque – only equality testing is stable. Note that it is not guaranteed which values new threads will return, and this may change across Rust versions. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1039)### impl Clone for ThreadId [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1039)#### fn clone(&self) -> ThreadId Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1039)### impl Debug for ThreadId [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1039)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1039)### impl Hash for ThreadId [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1039)#### fn hash<\_\_H: Hasher>(&self, state: &mut \_\_H) Feeds this value into the given [`Hasher`](../hash/trait.hasher "Hasher"). [Read more](../hash/trait.hash#tymethod.hash) [source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0 · #### fn hash\_slice<H>(data: &[Self], state: &mut H)where H: [Hasher](../hash/trait.hasher "trait std::hash::Hasher"), Feeds a slice of this type into the given [`Hasher`](../hash/trait.hasher "Hasher"). [Read more](../hash/trait.hash#method.hash_slice) [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1039)### impl PartialEq<ThreadId> for ThreadId [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1039)#### fn eq(&self, other: &ThreadId) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)1.0.0 · #### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1039)### impl Copy for ThreadId [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1039)### impl Eq for ThreadId [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1039)### impl StructuralEq for ThreadId [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1039)### impl StructuralPartialEq for ThreadId Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for ThreadId ### impl Send for ThreadId ### impl Sync for ThreadId ### impl Unpin for ThreadId ### impl UnwindSafe for ThreadId Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Module std::thread Module std::thread ================== Native threads. ### The threading model An executing Rust program consists of a collection of native OS threads, each with their own stack and local state. Threads can be named, and provide some built-in support for low-level synchronization. Communication between threads can be done through [channels](../sync/mpsc/index), Rust’s message-passing types, along with [other forms of thread synchronization](../sync/index) and shared-memory data structures. In particular, types that are guaranteed to be threadsafe are easily shared between threads using the atomically-reference-counted container, [`Arc`](../sync/struct.arc "Arc"). Fatal logic errors in Rust cause *thread panic*, during which a thread will unwind the stack, running destructors and freeing owned resources. While not meant as a ‘try/catch’ mechanism, panics in Rust can nonetheless be caught (unless compiling with `panic=abort`) with [`catch_unwind`](../panic/fn.catch_unwind) and recovered from, or alternatively be resumed with [`resume_unwind`](../panic/fn.resume_unwind). If the panic is not caught the thread will exit, but the panic may optionally be detected from a different thread with [`join`](struct.joinhandle#method.join). If the main thread panics without the panic being caught, the application will exit with a non-zero exit code. When the main thread of a Rust program terminates, the entire program shuts down, even if other threads are still running. However, this module provides convenient facilities for automatically waiting for the termination of a thread (i.e., join). ### Spawning a thread A new thread can be spawned using the [`thread::spawn`](fn.spawn "spawn") function: ``` use std::thread; thread::spawn(move || { // some work here }); ``` In this example, the spawned thread is “detached,” which means that there is no way for the program to learn when the spawned thread completes or otherwise terminates. To learn when a thread completes, it is necessary to capture the [`JoinHandle`](struct.joinhandle "JoinHandle") object that is returned by the call to [`spawn`](fn.spawn "spawn"), which provides a `join` method that allows the caller to wait for the completion of the spawned thread: ``` use std::thread; let thread_join_handle = thread::spawn(move || { // some work here }); // some work here let res = thread_join_handle.join(); ``` The [`join`](struct.joinhandle#method.join) method returns a [`thread::Result`](type.result) containing [`Ok`](../result/enum.result#variant.Ok) of the final value produced by the spawned thread, or [`Err`](../result/enum.result#variant.Err) of the value given to a call to [`panic!`](../macro.panic "panic!") if the thread panicked. Note that there is no parent/child relationship between a thread that spawns a new thread and the thread being spawned. In particular, the spawned thread may or may not outlive the spawning thread, unless the spawning thread is the main thread. ### Configuring threads A new thread can be configured before it is spawned via the [`Builder`](struct.builder "Builder") type, which currently allows you to set the name and stack size for the thread: ``` use std::thread; thread::Builder::new().name("thread1".to_string()).spawn(move || { println!("Hello, world!"); }); ``` ### The `Thread` type Threads are represented via the [`Thread`](struct.thread "Thread") type, which you can get in one of two ways: * By spawning a new thread, e.g., using the [`thread::spawn`](fn.spawn "spawn") function, and calling [`thread`](struct.joinhandle#method.thread "JoinHandle::thread") on the [`JoinHandle`](struct.joinhandle "JoinHandle"). * By requesting the current thread, using the [`thread::current`](fn.current) function. The [`thread::current`](fn.current) function is available even for threads not spawned by the APIs of this module. ### Thread-local storage This module also provides an implementation of thread-local storage for Rust programs. Thread-local storage is a method of storing data into a global variable that each thread in the program will have its own copy of. Threads do not share this data, so accesses do not need to be synchronized. A thread-local key owns the value it contains and will destroy the value when the thread exits. It is created with the [`thread_local!`](../macro.thread_local) macro and can contain any value that is `'static` (no borrowed pointers). It provides an accessor function, [`with`](struct.localkey#method.with), that yields a shared reference to the value to the specified closure. Thread-local keys allow only shared access to values, as there would be no way to guarantee uniqueness if mutable borrows were allowed. Most values will want to make use of some form of **interior mutability** through the [`Cell`](../cell/struct.cell) or [`RefCell`](../cell/struct.refcell) types. ### Naming threads Threads are able to have associated names for identification purposes. By default, spawned threads are unnamed. To specify a name for a thread, build the thread with [`Builder`](struct.builder "Builder") and pass the desired thread name to [`Builder::name`](struct.builder#method.name "Builder::name"). To retrieve the thread name from within the thread, use [`Thread::name`](struct.thread#method.name "Thread::name"). A couple of examples where the name of a thread gets used: * If a panic occurs in a named thread, the thread name will be printed in the panic message. * The thread name is provided to the OS where applicable (e.g., `pthread_setname_np` in unix-like platforms). ### Stack size The default stack size for spawned threads is 2 MiB, though this particular stack size is subject to change in the future. There are two ways to manually specify the stack size for spawned threads: * Build the thread with [`Builder`](struct.builder "Builder") and pass the desired stack size to [`Builder::stack_size`](struct.builder#method.stack_size "Builder::stack_size"). * Set the `RUST_MIN_STACK` environment variable to an integer representing the desired stack size (in bytes). Note that setting [`Builder::stack_size`](struct.builder#method.stack_size "Builder::stack_size") will override this. Note that the stack size of the main thread is *not* determined by Rust. Structs ------- [AccessError](struct.accesserror "std::thread::AccessError struct") An error returned by [`LocalKey::try_with`](struct.localkey#method.try_with). [Builder](struct.builder "std::thread::Builder struct") Thread factory, which can be used in order to configure the properties of a new thread. [JoinHandle](struct.joinhandle "std::thread::JoinHandle struct") An owned permission to join on a thread (block on its termination). [LocalKey](struct.localkey "std::thread::LocalKey struct") A thread local storage key which owns its contents. [Scope](struct.scope "std::thread::Scope struct") A scope to spawn scoped threads in. [ScopedJoinHandle](struct.scopedjoinhandle "std::thread::ScopedJoinHandle struct") An owned permission to join on a scoped thread (block on its termination). [Thread](struct.thread "std::thread::Thread struct") A handle to a thread. [ThreadId](struct.threadid "std::thread::ThreadId struct") A unique identifier for a running thread. Functions --------- [available\_parallelism](fn.available_parallelism "std::thread::available_parallelism fn") Returns an estimate of the default amount of parallelism a program should use. [current](fn.current "std::thread::current fn") Gets a handle to the thread that invokes it. [panicking](fn.panicking "std::thread::panicking fn") Determines whether the current thread is unwinding because of panic. [park](fn.park "std::thread::park fn") Blocks unless or until the current thread’s token is made available. [park\_timeout](fn.park_timeout "std::thread::park_timeout fn") Blocks unless or until the current thread’s token is made available or the specified duration has been reached (may wake spuriously). [park\_timeout\_ms](fn.park_timeout_ms "std::thread::park_timeout_ms fn")Deprecated Use [`park_timeout`](fn.park_timeout "park_timeout"). [scope](fn.scope "std::thread::scope fn") Create a scope for spawning scoped threads. [sleep](fn.sleep "std::thread::sleep fn") Puts the current thread to sleep for at least the specified amount of time. [sleep\_ms](fn.sleep_ms "std::thread::sleep_ms fn")Deprecated Puts the current thread to sleep for at least the specified amount of time. [spawn](fn.spawn "std::thread::spawn fn") Spawns a new thread, returning a [`JoinHandle`](struct.joinhandle "JoinHandle") for it. [yield\_now](fn.yield_now "std::thread::yield_now fn") Cooperatively gives up a timeslice to the OS scheduler. Type Definitions ---------------- [Result](type.result "std::thread::Result type") A specialized [`Result`](../result/enum.result) type for threads. rust Function std::thread::park Function std::thread::park ========================== ``` pub fn park() ``` Blocks unless or until the current thread’s token is made available. A call to `park` does not guarantee that the thread will remain parked forever, and callers should be prepared for this possibility. park and unpark --------------- Every thread is equipped with some basic low-level blocking support, via the [`thread::park`](fn.park "park") function and [`thread::Thread::unpark`](struct.thread#method.unpark) method. [`park`](fn.park "park") blocks the current thread, which can then be resumed from another thread by calling the [`unpark`](struct.thread#method.unpark) method on the blocked thread’s handle. Conceptually, each [`Thread`](struct.thread "Thread") handle has an associated token, which is initially not present: * The [`thread::park`](fn.park "park") function blocks the current thread unless or until the token is available for its thread handle, at which point it atomically consumes the token. It may also return *spuriously*, without consuming the token. [`thread::park_timeout`](fn.park_timeout) does the same, but allows specifying a maximum time to block the thread for. * The [`unpark`](struct.thread#method.unpark) method on a [`Thread`](struct.thread "Thread") atomically makes the token available if it wasn’t already. Because the token is initially absent, [`unpark`](struct.thread#method.unpark) followed by [`park`](fn.park "park") will result in the second call returning immediately. In other words, each [`Thread`](struct.thread "Thread") acts a bit like a spinlock that can be locked and unlocked using `park` and `unpark`. Notice that being unblocked does not imply any synchronization with someone that unparked this thread, it could also be spurious. For example, it would be a valid, but inefficient, implementation to make both [`park`](fn.park "park") and [`unpark`](struct.thread#method.unpark) return immediately without doing anything. The API is typically used by acquiring a handle to the current thread, placing that handle in a shared data structure so that other threads can find it, and then `park`ing in a loop. When some desired condition is met, another thread calls [`unpark`](struct.thread#method.unpark) on the handle. The motivation for this design is twofold: * It avoids the need to allocate mutexes and condvars when building new synchronization primitives; the threads already provide basic blocking/signaling. * It can be implemented very efficiently on many platforms. Examples -------- ``` use std::thread; use std::sync::{Arc, atomic::{Ordering, AtomicBool}}; use std::time::Duration; let flag = Arc::new(AtomicBool::new(false)); let flag2 = Arc::clone(&flag); let parked_thread = thread::spawn(move || { // We want to wait until the flag is set. We *could* just spin, but using // park/unpark is more efficient. while !flag2.load(Ordering::Acquire) { println!("Parking thread"); thread::park(); // We *could* get here spuriously, i.e., way before the 10ms below are over! // But that is no problem, we are in a loop until the flag is set anyway. println!("Thread unparked"); } println!("Flag received"); }); // Let some time pass for the thread to be spawned. thread::sleep(Duration::from_millis(10)); // Set the flag, and let the thread wake up. // There is no race condition here, if `unpark` // happens first, `park` will return immediately. // Hence there is no risk of a deadlock. flag.store(true, Ordering::Release); println!("Unpark the thread"); parked_thread.thread().unpark(); parked_thread.join().unwrap(); ```
programming_docs
rust Struct std::thread::AccessError Struct std::thread::AccessError =============================== ``` #[non_exhaustive]pub struct AccessError; ``` An error returned by [`LocalKey::try_with`](struct.localkey#method.try_with). Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#372)### impl Clone for AccessError [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#372)#### fn clone(&self) -> AccessError Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#376-380)### impl Debug for AccessError [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#377-379)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#383-387)### impl Display for AccessError [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#384-386)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#390)### impl Error for AccessError [source](https://doc.rust-lang.org/src/core/error.rs.html#83)1.30.0 · #### fn source(&self) -> Option<&(dyn Error + 'static)> The lower-level source of this error, if any. [Read more](../error/trait.error#method.source) [source](https://doc.rust-lang.org/src/core/error.rs.html#109)1.0.0 · #### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to\_string() [Read more](../error/trait.error#method.description) [source](https://doc.rust-lang.org/src/core/error.rs.html#119)1.0.0 · #### fn cause(&self) -> Option<&dyn Error> 👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting [source](https://doc.rust-lang.org/src/core/error.rs.html#193)#### fn provide(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301)) Provides type based access to context intended for error reports. [Read more](../error/trait.error#method.provide) [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#372)### impl PartialEq<AccessError> for AccessError [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#372)#### fn eq(&self, other: &AccessError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)1.0.0 · #### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#372)### impl Copy for AccessError [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#372)### impl Eq for AccessError [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#372)### impl StructuralEq for AccessError [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#372)### impl StructuralPartialEq for AccessError Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for AccessError ### impl Send for AccessError ### impl Sync for AccessError ### impl Unpin for AccessError ### impl UnwindSafe for AccessError Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/error.rs.html#197)### impl<E> Provider for Ewhere E: [Error](../error/trait.error "trait std::error::Error") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/error.rs.html#201)#### fn provide(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`provide_any` [#96024](https://github.com/rust-lang/rust/issues/96024)) Data providers should implement this method to provide *all* values they are able to provide by using `demand`. [Read more](../any/trait.provider#tymethod.provide) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2500)### impl<T> ToString for Twhere T: [Display](../fmt/trait.display "trait std::fmt::Display") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2506)#### default fn to\_string(&self) -> String Converts the given value to a `String`. [Read more](../string/trait.tostring#tymethod.to_string) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Function std::thread::panicking Function std::thread::panicking =============================== ``` pub fn panicking() -> bool ``` Determines whether the current thread is unwinding because of panic. A common use of this feature is to poison shared resources when writing unsafe code, by checking `panicking` when the `drop` is called. This is usually not needed when writing safe code, as [`Mutex`es](../sync/struct.mutex) already poison themselves when a thread panics while holding the lock. This can also be used in multithreaded applications, in order to send a message to other threads warning that a thread has panicked (e.g., for monitoring purposes). Examples -------- ⓘ ``` use std::thread; struct SomeStruct; impl Drop for SomeStruct { fn drop(&mut self) { if thread::panicking() { println!("dropped while unwinding"); } else { println!("dropped while not unwinding"); } } } { print!("a: "); let a = SomeStruct; } { print!("b: "); let b = SomeStruct; panic!() } ``` rust Function std::thread::park_timeout_ms Function std::thread::park\_timeout\_ms ======================================= ``` pub fn park_timeout_ms(ms: u32) ``` 👎Deprecated since 1.6.0: replaced by `std::thread::park_timeout` Use [`park_timeout`](fn.park_timeout "park_timeout"). Blocks unless or until the current thread’s token is made available or the specified duration has been reached (may wake spuriously). The semantics of this function are equivalent to [`park`](fn.park "park") except that the thread will be blocked for roughly no longer than `dur`. This method should not be used for precise timing due to anomalies such as preemption or platform differences that might not cause the maximum amount of time waited to be precisely `ms` long. See the [park documentation](fn.park "park") for more detail. rust Function std::thread::park_timeout Function std::thread::park\_timeout =================================== ``` pub fn park_timeout(dur: Duration) ``` Blocks unless or until the current thread’s token is made available or the specified duration has been reached (may wake spuriously). The semantics of this function are equivalent to [`park`](fn.park "park") except that the thread will be blocked for roughly no longer than `dur`. This method should not be used for precise timing due to anomalies such as preemption or platform differences that might not cause the maximum amount of time waited to be precisely `dur` long. See the [park documentation](fn.park "park") for more details. Platform-specific behavior -------------------------- Platforms which do not support nanosecond precision for sleeping will have `dur` rounded up to the nearest granularity of time they can sleep for. Examples -------- Waiting for the complete expiration of the timeout: ``` use std::thread::park_timeout; use std::time::{Instant, Duration}; let timeout = Duration::from_secs(2); let beginning_park = Instant::now(); let mut timeout_remaining = timeout; loop { park_timeout(timeout_remaining); let elapsed = beginning_park.elapsed(); if elapsed >= timeout { break; } println!("restarting park_timeout after {elapsed:?}"); timeout_remaining = timeout - elapsed; } ``` rust Function std::thread::spawn Function std::thread::spawn =========================== ``` pub fn spawn<F, T>(f: F) -> JoinHandle<T>where    F: FnOnce() -> T,    F: Send + 'static,    T: Send + 'static, ``` Spawns a new thread, returning a [`JoinHandle`](struct.joinhandle "JoinHandle") for it. The join handle provides a [`join`](struct.joinhandle#method.join) method that can be used to join the spawned thread. If the spawned thread panics, [`join`](struct.joinhandle#method.join) will return an [`Err`](../result/enum.result#variant.Err) containing the argument given to [`panic!`](../macro.panic "panic!"). If the join handle is dropped, the spawned thread will implicitly be *detached*. In this case, the spawned thread may no longer be joined. (It is the responsibility of the program to either eventually join threads it creates or detach them; otherwise, a resource leak will result.) This call will create a thread using default parameters of [`Builder`](struct.builder "Builder"), if you want to specify the stack size or the name of the thread, use this API instead. As you can see in the signature of `spawn` there are two constraints on both the closure given to `spawn` and its return value, let’s explain them: * The `'static` constraint means that the closure and its return value must have a lifetime of the whole program execution. The reason for this is that threads can outlive the lifetime they have been created in. Indeed if the thread, and by extension its return value, can outlive their caller, we need to make sure that they will be valid afterwards, and since we *can’t* know when it will return we need to have them valid as long as possible, that is until the end of the program, hence the `'static` lifetime. * The [`Send`](../marker/trait.send "Send") constraint is because the closure will need to be passed *by value* from the thread where it is spawned to the new thread. Its return value will need to be passed from the new thread to the thread where it is `join`ed. As a reminder, the [`Send`](../marker/trait.send "Send") marker trait expresses that it is safe to be passed from thread to thread. [`Sync`](../marker/trait.sync "Sync") expresses that it is safe to have a reference be passed from thread to thread. Panics ------ Panics if the OS fails to create a thread; use [`Builder::spawn`](struct.builder#method.spawn "Builder::spawn") to recover from such errors. Examples -------- Creating a thread. ``` use std::thread; let handler = thread::spawn(|| { // thread code }); handler.join().unwrap(); ``` As mentioned in the module documentation, threads are usually made to communicate using [`channels`](../sync/mpsc/index), here is how it usually looks. This example also shows how to use `move`, in order to give ownership of values to a thread. ``` use std::thread; use std::sync::mpsc::channel; let (tx, rx) = channel(); let sender = thread::spawn(move || { tx.send("Hello, thread".to_owned()) .expect("Unable to send on channel"); }); let receiver = thread::spawn(move || { let value = rx.recv().expect("Unable to receive from channel"); println!("{value}"); }); sender.join().expect("The sender thread has panicked"); receiver.join().expect("The receiver thread has panicked"); ``` A thread can also return a value through its [`JoinHandle`](struct.joinhandle "JoinHandle"), you can use this to make asynchronous computations (futures might be more appropriate though). ``` use std::thread; let computation = thread::spawn(|| { // Some expensive computation. 42 }); let result = computation.join().unwrap(); println!("{result}"); ``` rust Struct std::thread::JoinHandle Struct std::thread::JoinHandle ============================== ``` pub struct JoinHandle<T>(_); ``` An owned permission to join on a thread (block on its termination). A `JoinHandle` *detaches* the associated thread when it is dropped, which means that there is no longer any handle to the thread and no way to `join` on it. Due to platform restrictions, it is not possible to [`Clone`](../clone/trait.clone "Clone") this handle: the ability to join a thread is a uniquely-owned permission. This `struct` is created by the [`thread::spawn`](fn.spawn) function and the [`thread::Builder::spawn`](struct.builder#method.spawn) method. Examples -------- Creation from [`thread::spawn`](fn.spawn): ``` use std::thread; let join_handle: thread::JoinHandle<_> = thread::spawn(|| { // some work here }); ``` Creation from [`thread::Builder::spawn`](struct.builder#method.spawn): ``` use std::thread; let builder = thread::Builder::new(); let join_handle: thread::JoinHandle<_> = builder.spawn(|| { // some work here }).unwrap(); ``` A thread being detached and outliving the thread that spawned it: ``` use std::thread; use std::time::Duration; let original_thread = thread::spawn(|| { let _detached_thread = thread::spawn(|| { // Here we sleep to make sure that the first thread returns before. thread::sleep(Duration::from_millis(10)); // This will be called, even though the JoinHandle is dropped. println!("♫ Still alive ♫"); }); }); original_thread.join().expect("The thread being joined has panicked"); println!("Original thread is joined."); // We make sure that the new thread has time to run, before the main // thread returns. thread::sleep(Duration::from_millis(1000)); ``` Implementations --------------- [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1465-1540)### impl<T> JoinHandle<T> [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1484-1486)#### pub fn thread(&self) -> &Thread Extracts a handle to the underlying thread. ##### Examples ``` use std::thread; let builder = thread::Builder::new(); let join_handle: thread::JoinHandle<_> = builder.spawn(|| { // some work here }).unwrap(); let thread = join_handle.thread(); println!("thread id: {:?}", thread.id()); ``` [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1522-1524)#### pub fn join(self) -> Result<T> Waits for the associated thread to finish. This function will return immediately if the associated thread has already finished. In terms of [atomic memory orderings](../sync/atomic/index), the completion of the associated thread synchronizes with this function returning. In other words, all operations performed by that thread [happen before](https://doc.rust-lang.org/nomicon/atomics.html#data-accesses) all operations that happen after `join` returns. If the associated thread panics, [`Err`](../result/enum.result#variant.Err) is returned with the parameter given to [`panic!`](../macro.panic "panic!"). ##### Panics This function may panic on some platforms if a thread attempts to join itself or otherwise may create a deadlock with joining threads. ##### Examples ``` use std::thread; let builder = thread::Builder::new(); let join_handle: thread::JoinHandle<_> = builder.spawn(|| { // some work here }).unwrap(); join_handle.join().expect("Couldn't join on the associated thread"); ``` [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1537-1539)1.61.0 · #### pub fn is\_finished(&self) -> bool Checks if the associated thread has finished running its main function. `is_finished` supports implementing a non-blocking join operation, by checking `is_finished`, and calling `join` if it returns `true`. This function does not block. To block while waiting on the thread to finish, use [`join`](struct.joinhandle#method.join "Self::join"). This might return `true` for a brief moment after the thread’s main function has returned, but before the thread itself has stopped running. However, once this returns `true`, [`join`](struct.joinhandle#method.join "Self::join") can be expected to return quickly, without blocking for any significant amount of time. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#563-568)1.63.0 · ### impl<T> AsHandle for JoinHandle<T> Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#565-567)#### fn as\_handle(&self) -> BorrowedHandle<'\_> Borrows the handle. [Read more](../os/windows/io/trait.ashandle#tymethod.as_handle) [source](https://doc.rust-lang.org/src/std/os/windows/thread.rs.html#12-17)1.9.0 · ### impl<T> AsRawHandle for JoinHandle<T> Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/thread.rs.html#14-16)#### fn as\_raw\_handle(&self) -> RawHandle Extracts the raw handle. [Read more](../os/windows/io/trait.asrawhandle#tymethod.as_raw_handle) [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1555-1559)1.16.0 · ### impl<T> Debug for JoinHandle<T> [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1556-1558)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#571-576)1.63.0 · ### impl<T> From<JoinHandle<T>> for OwnedHandle Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#573-575)#### fn from(join\_handle: JoinHandle<T>) -> OwnedHandle Converts to this type from the input type. [source](https://doc.rust-lang.org/src/std/os/windows/thread.rs.html#20-25)1.9.0 · ### impl<T> IntoRawHandle for JoinHandle<T> Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/thread.rs.html#22-24)#### fn into\_raw\_handle(self) -> RawHandle Consumes this object, returning the raw underlying handle. [Read more](../os/windows/io/trait.intorawhandle#tymethod.into_raw_handle) [source](https://doc.rust-lang.org/src/std/os/unix/thread.rs.html#33-41)1.9.0 · ### impl<T> JoinHandleExt for JoinHandle<T> Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/thread.rs.html#34-36)#### fn as\_pthread\_t(&self) -> RawPthread Extracts the raw pthread\_t without taking ownership [source](https://doc.rust-lang.org/src/std/os/unix/thread.rs.html#38-40)#### fn into\_pthread\_t(self) -> RawPthread Consumes the thread, returning the raw pthread\_t [Read more](../os/unix/thread/trait.joinhandleext#tymethod.into_pthread_t) [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1461)1.29.0 · ### impl<T> Send for JoinHandle<T> [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1463)1.29.0 · ### impl<T> Sync for JoinHandle<T> Auto Trait Implementations -------------------------- ### impl<T> !RefUnwindSafe for JoinHandle<T> ### impl<T> Unpin for JoinHandle<T> ### impl<T> !UnwindSafe for JoinHandle<T> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Function std::thread::current Function std::thread::current ============================= ``` pub fn current() -> Thread ``` Gets a handle to the thread that invokes it. Examples -------- Getting a handle to the current thread with `thread::current()`: ``` use std::thread; let handler = thread::Builder::new() .name("named thread".into()) .spawn(|| { let handle = thread::current(); assert_eq!(handle.name(), Some("named thread")); }) .unwrap(); handler.join().unwrap(); ``` rust Function std::thread::sleep_ms Function std::thread::sleep\_ms =============================== ``` pub fn sleep_ms(ms: u32) ``` 👎Deprecated since 1.6.0: replaced by `std::thread::sleep` Puts the current thread to sleep for at least the specified amount of time. The thread may sleep longer than the duration specified due to scheduling specifics or platform-dependent functionality. It will never sleep less. This function is blocking, and should not be used in `async` functions. Platform-specific behavior -------------------------- On Unix platforms, the underlying syscall may be interrupted by a spurious wakeup or signal handler. To ensure the sleep occurs for at least the specified duration, this function may invoke that system call multiple times. Examples -------- ``` use std::thread; // Let's sleep for 2 seconds: thread::sleep_ms(2000); ``` rust Struct std::thread::Scope Struct std::thread::Scope ========================= ``` pub struct Scope<'scope, 'env: 'scope> { /* private fields */ } ``` A scope to spawn scoped threads in. See [`scope`](fn.scope "scope") for details. Implementations --------------- [source](https://doc.rust-lang.org/src/std/thread/scoped.rs.html#163-196)### impl<'scope, 'env> Scope<'scope, 'env> [source](https://doc.rust-lang.org/src/std/thread/scoped.rs.html#189-195)#### pub fn spawn<F, T>(&'scope self, f: F) -> ScopedJoinHandle<'scope, T>where F: [FnOnce](../ops/trait.fnonce "trait std::ops::FnOnce")() -> T + [Send](../marker/trait.send "trait std::marker::Send") + 'scope, T: [Send](../marker/trait.send "trait std::marker::Send") + 'scope, Spawns a new thread within a scope, returning a [`ScopedJoinHandle`](struct.scopedjoinhandle "ScopedJoinHandle") for it. Unlike non-scoped threads, threads spawned with this function may borrow non-`'static` data from the outside the scope. See [`scope`](fn.scope "scope") for details. The join handle provides a [`join`](struct.scopedjoinhandle#method.join) method that can be used to join the spawned thread. If the spawned thread panics, [`join`](struct.scopedjoinhandle#method.join) will return an [`Err`](../result/enum.result#variant.Err "Err") containing the panic payload. If the join handle is dropped, the spawned thread will implicitly joined at the end of the scope. In that case, if the spawned thread panics, [`scope`](fn.scope "scope") will panic after all threads are joined. This call will create a thread using default parameters of [`Builder`](struct.builder "Builder"). If you want to specify the stack size or the name of the thread, use [`Builder::spawn_scoped`](struct.builder#method.spawn_scoped "Builder::spawn_scoped") instead. ##### Panics Panics if the OS fails to create a thread; use [`Builder::spawn_scoped`](struct.builder#method.spawn_scoped "Builder::spawn_scoped") to recover from such errors. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/thread/scoped.rs.html#328-336)### impl Debug for Scope<'\_, '\_> [source](https://doc.rust-lang.org/src/std/thread/scoped.rs.html#329-335)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) Auto Trait Implementations -------------------------- ### impl<'scope, 'env> RefUnwindSafe for Scope<'scope, 'env> ### impl<'scope, 'env> Send for Scope<'scope, 'env> ### impl<'scope, 'env> Sync for Scope<'scope, 'env> ### impl<'scope, 'env> Unpin for Scope<'scope, 'env> ### impl<'scope, 'env> !UnwindSafe for Scope<'scope, 'env> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Struct std::thread::Thread Struct std::thread::Thread ========================== ``` pub struct Thread { /* private fields */ } ``` A handle to a thread. Threads are represented via the `Thread` type, which you can get in one of two ways: * By spawning a new thread, e.g., using the [`thread::spawn`](fn.spawn "spawn") function, and calling [`thread`](struct.joinhandle#method.thread "JoinHandle::thread") on the [`JoinHandle`](struct.joinhandle "JoinHandle"). * By requesting the current thread, using the [`thread::current`](fn.current) function. The [`thread::current`](fn.current) function is available even for threads not spawned by the APIs of this module. There is usually no need to create a `Thread` struct yourself, one should instead use a function like `spawn` to create new threads, see the docs of [`Builder`](struct.builder "Builder") and [`spawn`](fn.spawn "spawn") for more details. Implementations --------------- [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1146-1269)### impl Thread [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1199-1201)#### pub fn unpark(&self) Atomically makes the handle’s token available if it is not already. Every thread is equipped with some basic low-level blocking support, via the [`park`](fn.park "park") function and the `unpark()` method. These can be used as a more CPU-efficient implementation of a spinlock. See the [park documentation](fn.park "park") for more details. ##### Examples ``` use std::thread; use std::time::Duration; let parked_thread = thread::Builder::new() .spawn(|| { println!("Parking thread"); thread::park(); println!("Thread unparked"); }) .unwrap(); // Let some time pass for the thread to be spawned. thread::sleep(Duration::from_millis(10)); println!("Unpark the thread"); parked_thread.thread().unpark(); parked_thread.join().unwrap(); ``` [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1219-1221)1.19.0 · #### pub fn id(&self) -> ThreadId Gets the thread’s unique identifier. ##### Examples ``` use std::thread; let other_thread = thread::spawn(|| { thread::current().id() }); let other_thread_id = other_thread.join().unwrap(); assert!(thread::current().id() != other_thread_id); ``` [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1262-1264)#### pub fn name(&self) -> Option<&str> Gets the thread’s name. For more information about named threads, see [this module-level documentation](index#naming-threads). ##### Examples Threads by default have no name specified: ``` use std::thread; let builder = thread::Builder::new(); let handler = builder.spawn(|| { assert!(thread::current().name().is_none()); }).unwrap(); handler.join().unwrap(); ``` Thread with a specified name: ``` use std::thread; let builder = thread::Builder::new() .name("foo".into()); let handler = builder.spawn(|| { assert_eq!(thread::current().name(), Some("foo")) }).unwrap(); handler.join().unwrap(); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1122)### impl Clone for Thread [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1122)#### fn clone(&self) -> Thread Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1272-1279)### impl Debug for Thread [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#1273-1278)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for Thread ### impl Send for Thread ### impl Sync for Thread ### impl Unpin for Thread ### impl UnwindSafe for Thread Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Function std::thread::available_parallelism Function std::thread::available\_parallelism ============================================ ``` pub fn available_parallelism() -> Result<NonZeroUsize> ``` Returns an estimate of the default amount of parallelism a program should use. Parallelism is a resource. A given machine provides a certain capacity for parallelism, i.e., a bound on the number of computations it can perform simultaneously. This number often corresponds to the amount of CPUs a computer has, but it may diverge in various cases. Host environments such as VMs or container orchestrators may want to restrict the amount of parallelism made available to programs in them. This is often done to limit the potential impact of (unintentionally) resource-intensive programs on other programs running on the same machine. Limitations ----------- The purpose of this API is to provide an easy and portable way to query the default amount of parallelism the program should use. Among other things it does not expose information on NUMA regions, does not account for differences in (co)processor capabilities or current system load, and will not modify the program’s global state in order to more accurately query the amount of available parallelism. Where both fixed steady-state and burst limits are available the steady-state capacity will be used to ensure more predictable latencies. Resource limits can be changed during the runtime of a program, therefore the value is not cached and instead recomputed every time this function is called. It should not be called from hot code. The value returned by this function should be considered a simplified approximation of the actual amount of parallelism available at any given time. To get a more detailed or precise overview of the amount of parallelism available to the program, you may wish to use platform-specific APIs as well. The following platform limitations currently apply to `available_parallelism`: On Windows: * It may undercount the amount of parallelism available on systems with more than 64 logical CPUs. However, programs typically need specific support to take advantage of more than 64 logical CPUs, and in the absence of such support, the number returned by this function accurately reflects the number of logical CPUs the program can use by default. * It may overcount the amount of parallelism available on systems limited by process-wide affinity masks, or job object limitations. On Linux: * It may overcount the amount of parallelism available when limited by a process-wide affinity mask or cgroup quotas and `sched_getaffinity()` or cgroup fs can’t be queried, e.g. due to sandboxing. * It may undercount the amount of parallelism if the current thread’s affinity mask does not reflect the process’ cpuset, e.g. due to pinned threads. * If the process is in a cgroup v1 cpu controller, this may need to scan mountpoints to find the corresponding cgroup v1 controller, which may take time on systems with large numbers of mountpoints. (This does not apply to cgroup v2, or to processes not in a cgroup.) On all targets: * It may overcount the amount of parallelism available when running in a VM with CPU usage limits (e.g. an overcommitted host). Errors ------ This function will, but is not limited to, return errors in the following cases: * If the amount of parallelism is not known for the target platform. * If the program lacks permission to query the amount of parallelism made available to it. Examples -------- ``` use std::{io, thread}; fn main() -> io::Result<()> { let count = thread::available_parallelism()?.get(); assert!(count >= 1_usize); Ok(()) } ``` rust Struct std::thread::Builder Struct std::thread::Builder =========================== ``` pub struct Builder { /* private fields */ } ``` Thread factory, which can be used in order to configure the properties of a new thread. Methods can be chained on it in order to configure it. The two configurations available are: * [`name`](struct.builder#method.name): specifies an [associated name for the thread](index#naming-threads) * [`stack_size`](struct.builder#method.stack_size): specifies the [desired stack size for the thread](index#stack-size) The [`spawn`](struct.builder#method.spawn) method will take ownership of the builder and create an [`io::Result`](../io/type.result) to the thread handle with the given configuration. The [`thread::spawn`](fn.spawn) free function uses a `Builder` with default configuration and [`unwrap`](../result/enum.result#method.unwrap)s its return value. You may want to use [`spawn`](struct.builder#method.spawn) instead of [`thread::spawn`](fn.spawn), when you want to recover from a failure to launch a thread, indeed the free function will panic where the `Builder` method will return a [`io::Result`](../io/type.result). Examples -------- ``` use std::thread; let builder = thread::Builder::new(); let handler = builder.spawn(|| { // thread code }).unwrap(); handler.join().unwrap(); ``` Implementations --------------- [source](https://doc.rust-lang.org/src/std/thread/scoped.rs.html#198-257)### impl Builder [source](https://doc.rust-lang.org/src/std/thread/scoped.rs.html#246-256)1.63.0 · #### pub fn spawn\_scoped<'scope, 'env, F, T>( self, scope: &'scope Scope<'scope, 'env>, f: F) -> Result<ScopedJoinHandle<'scope, T>>where F: [FnOnce](../ops/trait.fnonce "trait std::ops::FnOnce")() -> T + [Send](../marker/trait.send "trait std::marker::Send") + 'scope, T: [Send](../marker/trait.send "trait std::marker::Send") + 'scope, Spawns a new scoped thread using the settings set through this `Builder`. Unlike [`Scope::spawn`](struct.scope#method.spawn "Scope::spawn"), this method yields an [`io::Result`](../io/type.result) to capture any failure to create the thread at the OS level. ##### Panics Panics if a thread name was set and it contained null bytes. ##### Example ``` use std::thread; let mut a = vec![1, 2, 3]; let mut x = 0; thread::scope(|s| { thread::Builder::new() .name("first".to_string()) .spawn_scoped(s, || { println!("hello from the {:?} scoped thread", thread::current().name()); // We can borrow `a` here. dbg!(&a); }) .unwrap(); thread::Builder::new() .name("second".to_string()) .spawn_scoped(s, || { println!("hello from the {:?} scoped thread", thread::current().name()); // We can even mutably borrow `x` here, // because no other threads are using it. x += a[0] + a[2]; }) .unwrap(); println!("hello from the main thread"); }); // After the scope, we can modify and access our variables again: a.push(4); assert_eq!(x, a.len()); ``` [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#282-553)### impl Builder [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#302-304)#### pub fn new() -> Builder Generates the base configuration for spawning a thread, from which configuration methods can be chained. ##### Examples ``` use std::thread; let builder = thread::Builder::new() .name("foo".into()) .stack_size(32 * 1024); let handler = builder.spawn(|| { // thread code }).unwrap(); handler.join().unwrap(); ``` [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#331-334)#### pub fn name(self, name: String) -> Builder Names the thread-to-be. Currently the name is used for identification only in panic messages. The name must not contain null bytes (`\0`). For more information about named threads, see [this module-level documentation](index#naming-threads). ##### Examples ``` use std::thread; let builder = thread::Builder::new() .name("foo".into()); let handler = builder.spawn(|| { assert_eq!(thread::current().name(), Some("foo")) }).unwrap(); handler.join().unwrap(); ``` [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#354-357)#### pub fn stack\_size(self, size: usize) -> Builder Sets the size of the stack (in bytes) for the new thread. The actual stack size may be greater than this value if the platform specifies a minimal stack size. For more information about the stack size for threads, see [this module-level documentation](index#stack-size). ##### Examples ``` use std::thread; let builder = thread::Builder::new().stack_size(32 * 1024); ``` [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#395-402)#### pub fn spawn<F, T>(self, f: F) -> Result<JoinHandle<T>>where F: [FnOnce](../ops/trait.fnonce "trait std::ops::FnOnce")() -> T, F: [Send](../marker/trait.send "trait std::marker::Send") + 'static, T: [Send](../marker/trait.send "trait std::marker::Send") + 'static, Spawns a new thread by taking ownership of the `Builder`, and returns an [`io::Result`](../io/type.result) to its [`JoinHandle`](struct.joinhandle "JoinHandle"). The spawned thread may outlive the caller (unless the caller thread is the main thread; the whole process is terminated when the main thread finishes). The join handle can be used to block on termination of the spawned thread, including recovering its panics. For a more complete documentation see [`thread::spawn`](fn.spawn "spawn"). ##### Errors Unlike the [`spawn`](fn.spawn "spawn") free function, this method yields an [`io::Result`](../io/type.result) to capture any failure to create the thread at the OS level. ##### Panics Panics if a thread name was set and it contained null bytes. ##### Examples ``` use std::thread; let builder = thread::Builder::new(); let handler = builder.spawn(|| { // thread code }).unwrap(); handler.join().unwrap(); ``` [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#463-470)#### pub unsafe fn spawn\_unchecked<'a, F, T>(self, f: F) -> Result<JoinHandle<T>>where F: [FnOnce](../ops/trait.fnonce "trait std::ops::FnOnce")() -> T, F: [Send](../marker/trait.send "trait std::marker::Send") + 'a, T: [Send](../marker/trait.send "trait std::marker::Send") + 'a, 🔬This is a nightly-only experimental API. (`thread_spawn_unchecked` [#55132](https://github.com/rust-lang/rust/issues/55132)) Spawns a new thread without any lifetime restrictions by taking ownership of the `Builder`, and returns an [`io::Result`](../io/type.result) to its [`JoinHandle`](struct.joinhandle "JoinHandle"). The spawned thread may outlive the caller (unless the caller thread is the main thread; the whole process is terminated when the main thread finishes). The join handle can be used to block on termination of the spawned thread, including recovering its panics. This method is identical to [`thread::Builder::spawn`](struct.builder#method.spawn "Builder::spawn"), except for the relaxed lifetime bounds, which render it unsafe. For a more complete documentation see [`thread::spawn`](fn.spawn "spawn"). ##### Errors Unlike the [`spawn`](fn.spawn "spawn") free function, this method yields an [`io::Result`](../io/type.result) to capture any failure to create the thread at the OS level. ##### Panics Panics if a thread name was set and it contained null bytes. ##### Safety The caller has to ensure that the spawned thread does not outlive any references in the supplied thread closure and its return type. This can be guaranteed in two ways: * ensure that [`join`](struct.joinhandle#method.join "JoinHandle::join") is called before any referenced data is dropped * use only types with `'static` lifetime bounds, i.e., those with no or only `'static` references (both [`thread::Builder::spawn`](struct.builder#method.spawn "Builder::spawn") and [`thread::spawn`](fn.spawn "spawn") enforce this property statically) ##### Examples ``` #![feature(thread_spawn_unchecked)] use std::thread; let builder = thread::Builder::new(); let x = 1; let thread_x = &x; let handler = unsafe { builder.spawn_unchecked(move || { println!("x = {}", *thread_x); }).unwrap() }; // caller has to ensure `join()` is called, otherwise // it is possible to access freed memory if `x` gets // dropped before the thread closure is executed! handler.join().unwrap(); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#274)### impl Debug for Builder [source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#274)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for Builder ### impl Send for Builder ### impl Sync for Builder ### impl Unpin for Builder ### impl UnwindSafe for Builder Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Function std::thread::scope Function std::thread::scope =========================== ``` pub fn scope<'env, F, T>(f: F) -> Twhere    F: for<'scope> FnOnce(&'scope Scope<'scope, 'env>) -> T, ``` Create a scope for spawning scoped threads. The function passed to `scope` will be provided a [`Scope`](struct.scope "Scope") object, through which scoped threads can be [spawned](struct.scope#method.spawn "Scope::spawn"). Unlike non-scoped threads, scoped threads can borrow non-`'static` data, as the scope guarantees all threads will be joined at the end of the scope. All threads spawned within the scope that haven’t been manually joined will be automatically joined before this function returns. Panics ------ If any of the automatically joined threads panicked, this function will panic. If you want to handle panics from spawned threads, [`join`](struct.scopedjoinhandle#method.join "ScopedJoinHandle::join") them before the end of the scope. Example ------- ``` use std::thread; let mut a = vec![1, 2, 3]; let mut x = 0; thread::scope(|s| { s.spawn(|| { println!("hello from the first scoped thread"); // We can borrow `a` here. dbg!(&a); }); s.spawn(|| { println!("hello from the second scoped thread"); // We can even mutably borrow `x` here, // because no other threads are using it. x += a[0] + a[2]; }); println!("hello from the main thread"); }); // After the scope, we can modify and access our variables again: a.push(4); assert_eq!(x, a.len()); ``` Lifetimes --------- Scoped threads involve two lifetimes: `'scope` and `'env`. The `'scope` lifetime represents the lifetime of the scope itself. That is: the time during which new scoped threads may be spawned, and also the time during which they might still be running. Once this lifetime ends, all scoped threads are joined. This lifetime starts within the `scope` function, before `f` (the argument to `scope`) starts. It ends after `f` returns and all scoped threads have been joined, but before `scope` returns. The `'env` lifetime represents the lifetime of whatever is borrowed by the scoped threads. This lifetime must outlast the call to `scope`, and thus cannot be smaller than `'scope`. It can be as small as the call to `scope`, meaning that anything that outlives this call, such as local variables defined right before the scope, can be borrowed by the scoped threads. The `'env: 'scope` bound is part of the definition of the `Scope` type. rust Struct std::thread::LocalKey Struct std::thread::LocalKey ============================ ``` pub struct LocalKey<T: 'static> { /* private fields */ } ``` A thread local storage key which owns its contents. This key uses the fastest possible implementation available to it for the target platform. It is instantiated with the [`thread_local!`](../macro.thread_local) macro and the primary method is the [`with`](struct.localkey#method.with) method. The [`with`](struct.localkey#method.with) method yields a reference to the contained value which cannot be sent across threads or escape the given closure. Initialization and Destruction ------------------------------ Initialization is dynamically performed on the first call to [`with`](struct.localkey#method.with) within a thread, and values that implement [`Drop`](../ops/trait.drop "Drop") get destructed when a thread exits. Some caveats apply, which are explained below. A `LocalKey`’s initializer cannot recursively depend on itself, and using a `LocalKey` in this way will cause the initializer to infinitely recurse on the first call to `with`. Examples -------- ``` use std::cell::RefCell; use std::thread; thread_local!(static FOO: RefCell<u32> = RefCell::new(1)); FOO.with(|f| { assert_eq!(*f.borrow(), 1); *f.borrow_mut() = 2; }); // each thread starts out with the initial value of 1 let t = thread::spawn(move|| { FOO.with(|f| { assert_eq!(*f.borrow(), 1); *f.borrow_mut() = 3; }); }); // wait for the thread to complete and bail out on panic t.join().unwrap(); // we retain our original value of 2 despite the child thread FOO.with(|f| { assert_eq!(*f.borrow(), 2); }); ``` Platform-specific behavior -------------------------- Note that a “best effort” is made to ensure that destructors for types stored in thread local storage are run, but not all platforms can guarantee that destructors will be run for all types in thread local storage. For example, there are a number of known caveats where destructors are not run: 1. On Unix systems when pthread-based TLS is being used, destructors will not be run for TLS values on the main thread when it exits. Note that the application will exit immediately after the main thread exits as well. 2. On all platforms it’s possible for TLS to re-initialize other TLS slots during destruction. Some platforms ensure that this cannot happen infinitely by preventing re-initialization of any slot that has been destroyed, but not all platforms have this guard. Those platforms that do not guard typically have a synthetic limit after which point no more destructors are run. 3. When the process exits on Windows systems, TLS destructors may only be run on the thread that causes the process to exit. This is because the other threads may be forcibly terminated. ### Synchronization in thread-local destructors On Windows, synchronization operations (such as [`JoinHandle::join`](struct.joinhandle#method.join)) in thread local destructors are prone to deadlocks and so should be avoided. This is because the [loader lock](https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices) is held while a destructor is run. The lock is acquired whenever a thread starts or exits or when a DLL is loaded or unloaded. Therefore these events are blocked for as long as a thread local destructor is running. Implementations --------------- [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#392-474)### impl<T: 'static> LocalKey<T> [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#417-425)#### pub fn with<F, R>(&'static self, f: F) -> Rwhere F: [FnOnce](../ops/trait.fnonce "trait std::ops::FnOnce")([&](../primitive.reference)T) -> R, Acquires a reference to the value in this TLS key. This will lazily initialize the value if this thread has not referenced this key yet. ##### Panics This function will `panic!()` if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#439-447)1.26.0 · #### pub fn try\_with<F, R>(&'static self, f: F) -> Result<R, AccessError>where F: [FnOnce](../ops/trait.fnonce "trait std::ops::FnOnce")([&](../primitive.reference)T) -> R, Acquires a reference to the value in this TLS key. This will lazily initialize the value if this thread has not referenced this key yet. If the key has been destroyed (which may happen if this is called in a destructor), this function will return an [`AccessError`](struct.accesserror "AccessError"). ##### Panics This function will still `panic!()` if the key is uninitialized and the key’s initializer panics. [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#476-604)### impl<T: 'static> LocalKey<Cell<T>> [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#505-514)#### pub fn set(&'static self, value: T) 🔬This is a nightly-only experimental API. (`local_key_cell_methods` [#92122](https://github.com/rust-lang/rust/issues/92122)) Sets or initializes the contained value. Unlike the other methods, this will *not* run the lazy initializer of the thread local. Instead, it will be directly initialized with the given value if it wasn’t initialized yet. ##### Panics Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### Examples ``` #![feature(local_key_cell_methods)] use std::cell::Cell; thread_local! { static X: Cell<i32> = panic!("!"); } // Calling X.get() here would result in a panic. X.set(123); // But X.set() is fine, as it skips the initializer above. assert_eq!(X.get(), 123); ``` [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#539-544)#### pub fn get(&'static self) -> Twhere T: [Copy](../marker/trait.copy "trait std::marker::Copy"), 🔬This is a nightly-only experimental API. (`local_key_cell_methods` [#92122](https://github.com/rust-lang/rust/issues/92122)) Returns a copy of the contained value. This will lazily initialize the value if this thread has not referenced this key yet. ##### Panics Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### Examples ``` #![feature(local_key_cell_methods)] use std::cell::Cell; thread_local! { static X: Cell<i32> = Cell::new(1); } assert_eq!(X.get(), 1); ``` [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#570-575)#### pub fn take(&'static self) -> Twhere T: [Default](../default/trait.default "trait std::default::Default"), 🔬This is a nightly-only experimental API. (`local_key_cell_methods` [#92122](https://github.com/rust-lang/rust/issues/92122)) Takes the contained value, leaving `Default::default()` in its place. This will lazily initialize the value if this thread has not referenced this key yet. ##### Panics Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### Examples ``` #![feature(local_key_cell_methods)] use std::cell::Cell; thread_local! { static X: Cell<Option<i32>> = Cell::new(Some(1)); } assert_eq!(X.take(), Some(1)); assert_eq!(X.take(), None); ``` [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#601-603)#### pub fn replace(&'static self, value: T) -> T 🔬This is a nightly-only experimental API. (`local_key_cell_methods` [#92122](https://github.com/rust-lang/rust/issues/92122)) Replaces the contained value, returning the old value. This will lazily initialize the value if this thread has not referenced this key yet. ##### Panics Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### Examples ``` #![feature(local_key_cell_methods)] use std::cell::Cell; thread_local! { static X: Cell<i32> = Cell::new(1); } assert_eq!(X.replace(2), 1); assert_eq!(X.replace(3), 2); ``` [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#606-780)### impl<T: 'static> LocalKey<RefCell<T>> [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#632-637)#### pub fn with\_borrow<F, R>(&'static self, f: F) -> Rwhere F: [FnOnce](../ops/trait.fnonce "trait std::ops::FnOnce")([&](../primitive.reference)T) -> R, 🔬This is a nightly-only experimental API. (`local_key_cell_methods` [#92122](https://github.com/rust-lang/rust/issues/92122)) Acquires a reference to the contained value. This will lazily initialize the value if this thread has not referenced this key yet. ##### Panics Panics if the value is currently mutably borrowed. Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### Example ``` #![feature(local_key_cell_methods)] use std::cell::RefCell; thread_local! { static X: RefCell<Vec<i32>> = RefCell::new(Vec::new()); } X.with_borrow(|v| assert!(v.is_empty())); ``` [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#666-671)#### pub fn with\_borrow\_mut<F, R>(&'static self, f: F) -> Rwhere F: [FnOnce](../ops/trait.fnonce "trait std::ops::FnOnce")([&mut](../primitive.reference) T) -> R, 🔬This is a nightly-only experimental API. (`local_key_cell_methods` [#92122](https://github.com/rust-lang/rust/issues/92122)) Acquires a mutable reference to the contained value. This will lazily initialize the value if this thread has not referenced this key yet. ##### Panics Panics if the value is currently borrowed. Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### Example ``` #![feature(local_key_cell_methods)] use std::cell::RefCell; thread_local! { static X: RefCell<Vec<i32>> = RefCell::new(Vec::new()); } X.with_borrow_mut(|v| v.push(1)); X.with_borrow(|v| assert_eq!(*v, vec![1])); ``` [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#703-712)#### pub fn set(&'static self, value: T) 🔬This is a nightly-only experimental API. (`local_key_cell_methods` [#92122](https://github.com/rust-lang/rust/issues/92122)) Sets or initializes the contained value. Unlike the other methods, this will *not* run the lazy initializer of the thread local. Instead, it will be directly initialized with the given value if it wasn’t initialized yet. ##### Panics Panics if the value is currently borrowed. Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### Examples ``` #![feature(local_key_cell_methods)] use std::cell::RefCell; thread_local! { static X: RefCell<Vec<i32>> = panic!("!"); } // Calling X.with() here would result in a panic. X.set(vec![1, 2, 3]); // But X.set() is fine, as it skips the initializer above. X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3])); ``` [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#745-750)#### pub fn take(&'static self) -> Twhere T: [Default](../default/trait.default "trait std::default::Default"), 🔬This is a nightly-only experimental API. (`local_key_cell_methods` [#92122](https://github.com/rust-lang/rust/issues/92122)) Takes the contained value, leaving `Default::default()` in its place. This will lazily initialize the value if this thread has not referenced this key yet. ##### Panics Panics if the value is currently borrowed. Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### Examples ``` #![feature(local_key_cell_methods)] use std::cell::RefCell; thread_local! { static X: RefCell<Vec<i32>> = RefCell::new(Vec::new()); } X.with_borrow_mut(|v| v.push(1)); let a = X.take(); assert_eq!(a, vec![1]); X.with_borrow(|v| assert!(v.is_empty())); ``` [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#777-779)#### pub fn replace(&'static self, value: T) -> T 🔬This is a nightly-only experimental API. (`local_key_cell_methods` [#92122](https://github.com/rust-lang/rust/issues/92122)) Replaces the contained value, returning the old value. ##### Panics Panics if the value is currently borrowed. Panics if the key currently has its destructor running, and it **may** panic if the destructor has previously been run for this thread. ##### Examples ``` #![feature(local_key_cell_methods)] use std::cell::RefCell; thread_local! { static X: RefCell<Vec<i32>> = RefCell::new(Vec::new()); } let prev = X.replace(vec![1, 2, 3]); assert!(prev.is_empty()); X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3])); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#118-122)1.16.0 · ### impl<T: 'static> Debug for LocalKey<T> [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#119-121)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) Auto Trait Implementations -------------------------- ### impl<T> RefUnwindSafe for LocalKey<T> ### impl<T> Send for LocalKey<T> ### impl<T> Sync for LocalKey<T> ### impl<T> Unpin for LocalKey<T> ### impl<T> UnwindSafe for LocalKey<T> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Function std::thread::sleep Function std::thread::sleep =========================== ``` pub fn sleep(dur: Duration) ``` Puts the current thread to sleep for at least the specified amount of time. The thread may sleep longer than the duration specified due to scheduling specifics or platform-dependent functionality. It will never sleep less. This function is blocking, and should not be used in `async` functions. Platform-specific behavior -------------------------- On Unix platforms, the underlying syscall may be interrupted by a spurious wakeup or signal handler. To ensure the sleep occurs for at least the specified duration, this function may invoke that system call multiple times. Platforms which do not support nanosecond precision for sleeping will have `dur` rounded up to the nearest granularity of time they can sleep for. Currently, specifying a zero duration on Unix platforms returns immediately without invoking the underlying [`nanosleep`](https://linux.die.net/man/2/nanosleep) syscall, whereas on Windows platforms the underlying [`Sleep`](https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep) syscall is always invoked. If the intention is to yield the current time-slice you may want to use [`yield_now`](fn.yield_now "yield_now") instead. Examples -------- ``` use std::{thread, time}; let ten_millis = time::Duration::from_millis(10); let now = time::Instant::now(); thread::sleep(ten_millis); assert!(now.elapsed() >= ten_millis); ```
programming_docs
rust Type Definition std::thread::Result Type Definition std::thread::Result =================================== ``` pub type Result<T> = Result<T, Box<dyn Any + Send + 'static>>; ``` A specialized [`Result`](../result/enum.result) type for threads. Indicates the manner in which a thread exited. The value contained in the `Result::Err` variant is the value the thread panicked with; that is, the argument the `panic!` macro was called with. Unlike with normal errors, this value doesn’t implement the [`Error`](../error/trait.error) trait. Thus, a sensible way to handle a thread panic is to either: 1. propagate the panic with [`std::panic::resume_unwind`](../panic/fn.resume_unwind) 2. or in case the thread is intended to be a subsystem boundary that is supposed to isolate system-level failures, match on the `Err` variant and handle the panic in an appropriate way A thread that completes without panicking is considered to exit successfully. Examples -------- Matching on the result of a joined thread: ``` use std::{fs, thread, panic}; fn copy_in_thread() -> thread::Result<()> { thread::spawn(|| { fs::copy("foo.txt", "bar.txt").unwrap(); }).join() } fn main() { match copy_in_thread() { Ok(_) => println!("copy succeeded"), Err(e) => panic::resume_unwind(e), } } ``` rust Function std::thread::yield_now Function std::thread::yield\_now ================================ ``` pub fn yield_now() ``` Cooperatively gives up a timeslice to the OS scheduler. This calls the underlying OS scheduler’s yield primitive, signaling that the calling thread is willing to give up its remaining timeslice so that the OS may schedule other threads on the CPU. A drawback of yielding in a loop is that if the OS does not have any other ready threads to run on the current CPU, the thread will effectively busy-wait, which wastes CPU time and energy. Therefore, when waiting for events of interest, a programmer’s first choice should be to use synchronization devices such as [`channel`](../sync/mpsc/index)s, [`Condvar`](../sync/struct.condvar)s, [`Mutex`](../sync/struct.mutex)es or [`join`](struct.joinhandle#method.join) since these primitives are implemented in a blocking manner, giving up the CPU until the event of interest has occurred which avoids repeated yielding. `yield_now` should thus be used only rarely, mostly in situations where repeated polling is required because there is no other suitable way to learn when an event of interest has occurred. Examples -------- ``` use std::thread; thread::yield_now(); ``` rust Struct std::thread::ScopedJoinHandle Struct std::thread::ScopedJoinHandle ==================================== ``` pub struct ScopedJoinHandle<'scope, T>(_); ``` An owned permission to join on a scoped thread (block on its termination). See [`Scope::spawn`](struct.scope#method.spawn "Scope::spawn") for details. Implementations --------------- [source](https://doc.rust-lang.org/src/std/thread/scoped.rs.html#259-325)### impl<'scope, T> ScopedJoinHandle<'scope, T> [source](https://doc.rust-lang.org/src/std/thread/scoped.rs.html#276-278)#### pub fn thread(&self) -> &Thread Extracts a handle to the underlying thread. ##### Examples ``` use std::thread; thread::scope(|s| { let t = s.spawn(|| { println!("hello"); }); println!("thread id: {:?}", t.thread().id()); }); ``` [source](https://doc.rust-lang.org/src/std/thread/scoped.rs.html#307-309)#### pub fn join(self) -> Result<T> Waits for the associated thread to finish. This function will return immediately if the associated thread has already finished. In terms of [atomic memory orderings](../sync/atomic/index), the completion of the associated thread synchronizes with this function returning. In other words, all operations performed by that thread [happen before](https://doc.rust-lang.org/nomicon/atomics.html#data-accesses) all operations that happen after `join` returns. If the associated thread panics, [`Err`](../result/enum.result#variant.Err "Err") is returned with the panic payload. ##### Examples ``` use std::thread; thread::scope(|s| { let t = s.spawn(|| { panic!("oh no"); }); assert!(t.join().is_err()); }); ``` [source](https://doc.rust-lang.org/src/std/thread/scoped.rs.html#322-324)#### pub fn is\_finished(&self) -> bool Checks if the associated thread has finished running its main function. `is_finished` supports implementing a non-blocking join operation, by checking `is_finished`, and calling `join` if it returns `false`. This function does not block. To block while waiting on the thread to finish, use [`join`](struct.scopedjoinhandle#method.join "Self::join"). This might return `true` for a brief moment after the thread’s main function has returned, but before the thread itself has stopped running. However, once this returns `true`, [`join`](struct.scopedjoinhandle#method.join "Self::join") can be expected to return quickly, without blocking for any significant amount of time. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/thread/scoped.rs.html#339-343)### impl<'scope, T> Debug for ScopedJoinHandle<'scope, T> [source](https://doc.rust-lang.org/src/std/thread/scoped.rs.html#340-342)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) Auto Trait Implementations -------------------------- ### impl<'scope, T> !RefUnwindSafe for ScopedJoinHandle<'scope, T> ### impl<'scope, T> Send for ScopedJoinHandle<'scope, T>where T: [Send](../marker/trait.send "trait std::marker::Send") + [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<'scope, T> Sync for ScopedJoinHandle<'scope, T>where T: [Send](../marker/trait.send "trait std::marker::Send") + [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<'scope, T> Unpin for ScopedJoinHandle<'scope, T> ### impl<'scope, T> !UnwindSafe for ScopedJoinHandle<'scope, T> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Module std::rc Module std::rc ============== Single-threaded reference-counting pointers. ‘Rc’ stands for ‘Reference Counted’. The type [`Rc<T>`](struct.rc "Rc") provides shared ownership of a value of type `T`, allocated in the heap. Invoking [`clone`](../clone/trait.clone#tymethod.clone) on [`Rc`](struct.rc "Rc") produces a new pointer to the same allocation in the heap. When the last [`Rc`](struct.rc "Rc") pointer to a given allocation is destroyed, the value stored in that allocation (often referred to as “inner value”) is also dropped. Shared references in Rust disallow mutation by default, and [`Rc`](struct.rc "Rc") is no exception: you cannot generally obtain a mutable reference to something inside an [`Rc`](struct.rc "Rc"). If you need mutability, put a [`Cell`](../cell/struct.cell) or [`RefCell`](../cell/struct.refcell) inside the [`Rc`](struct.rc "Rc"); see [an example of mutability inside an `Rc`](../cell/index#introducing-mutability-inside-of-something-immutable). [`Rc`](struct.rc "Rc") uses non-atomic reference counting. This means that overhead is very low, but an [`Rc`](struct.rc "Rc") cannot be sent between threads, and consequently [`Rc`](struct.rc "Rc") does not implement [`Send`](../marker/trait.send). As a result, the Rust compiler will check *at compile time* that you are not sending [`Rc`](struct.rc "Rc")s between threads. If you need multi-threaded, atomic reference counting, use [`sync::Arc`](../sync/struct.arc). The [`downgrade`](struct.rc#method.downgrade) method can be used to create a non-owning [`Weak`](struct.weak "Weak") pointer. A [`Weak`](struct.weak "Weak") pointer can be [`upgrade`](struct.weak#method.upgrade)d to an [`Rc`](struct.rc "Rc"), but this will return [`None`](../option/enum.option#variant.None "None") if the value stored in the allocation has already been dropped. In other words, `Weak` pointers do not keep the value inside the allocation alive; however, they *do* keep the allocation (the backing store for the inner value) alive. A cycle between [`Rc`](struct.rc "Rc") pointers will never be deallocated. For this reason, [`Weak`](struct.weak "Weak") is used to break cycles. For example, a tree could have strong [`Rc`](struct.rc "Rc") pointers from parent nodes to children, and [`Weak`](struct.weak "Weak") pointers from children back to their parents. `Rc<T>` automatically dereferences to `T` (via the [`Deref`](../ops/trait.deref) trait), so you can call `T`’s methods on a value of type [`Rc<T>`](struct.rc "Rc"). To avoid name clashes with `T`’s methods, the methods of [`Rc<T>`](struct.rc "Rc") itself are associated functions, called using [fully qualified syntax](../../book/ch19-03-advanced-traits#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name): ``` use std::rc::Rc; let my_rc = Rc::new(()); let my_weak = Rc::downgrade(&my_rc); ``` `Rc<T>`’s implementations of traits like `Clone` may also be called using fully qualified syntax. Some people prefer to use fully qualified syntax, while others prefer using method-call syntax. ``` use std::rc::Rc; let rc = Rc::new(()); // Method-call syntax let rc2 = rc.clone(); // Fully qualified syntax let rc3 = Rc::clone(&rc); ``` [`Weak<T>`](struct.weak "Weak") does not auto-dereference to `T`, because the inner value may have already been dropped. Cloning references ------------------ Creating a new reference to the same allocation as an existing reference counted pointer is done using the `Clone` trait implemented for [`Rc<T>`](struct.rc "Rc") and [`Weak<T>`](struct.weak "Weak"). ``` use std::rc::Rc; let foo = Rc::new(vec![1.0, 2.0, 3.0]); // The two syntaxes below are equivalent. let a = foo.clone(); let b = Rc::clone(&foo); // a and b both point to the same memory location as foo. ``` The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly the meaning of the code. In the example above, this syntax makes it easier to see that this code is creating a new reference rather than copying the whole content of foo. Examples -------- Consider a scenario where a set of `Gadget`s are owned by a given `Owner`. We want to have our `Gadget`s point to their `Owner`. We can’t do this with unique ownership, because more than one gadget may belong to the same `Owner`. [`Rc`](struct.rc "Rc") allows us to share an `Owner` between multiple `Gadget`s, and have the `Owner` remain allocated as long as any `Gadget` points at it. ``` use std::rc::Rc; struct Owner { name: String, // ...other fields } struct Gadget { id: i32, owner: Rc<Owner>, // ...other fields } fn main() { // Create a reference-counted `Owner`. let gadget_owner: Rc<Owner> = Rc::new( Owner { name: "Gadget Man".to_string(), } ); // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>` // gives us a new pointer to the same `Owner` allocation, incrementing // the reference count in the process. let gadget1 = Gadget { id: 1, owner: Rc::clone(&gadget_owner), }; let gadget2 = Gadget { id: 2, owner: Rc::clone(&gadget_owner), }; // Dispose of our local variable `gadget_owner`. drop(gadget_owner); // Despite dropping `gadget_owner`, we're still able to print out the name // of the `Owner` of the `Gadget`s. This is because we've only dropped a // single `Rc<Owner>`, not the `Owner` it points to. As long as there are // other `Rc<Owner>` pointing at the same `Owner` allocation, it will remain // live. The field projection `gadget1.owner.name` works because // `Rc<Owner>` automatically dereferences to `Owner`. println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name); println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name); // At the end of the function, `gadget1` and `gadget2` are destroyed, and // with them the last counted references to our `Owner`. Gadget Man now // gets destroyed as well. } ``` If our requirements change, and we also need to be able to traverse from `Owner` to `Gadget`, we will run into problems. An [`Rc`](struct.rc "Rc") pointer from `Owner` to `Gadget` introduces a cycle. This means that their reference counts can never reach 0, and the allocation will never be destroyed: a memory leak. In order to get around this, we can use [`Weak`](struct.weak "Weak") pointers. Rust actually makes it somewhat difficult to produce this loop in the first place. In order to end up with two values that point at each other, one of them needs to be mutable. This is difficult because [`Rc`](struct.rc "Rc") enforces memory safety by only giving out shared references to the value it wraps, and these don’t allow direct mutation. We need to wrap the part of the value we wish to mutate in a [`RefCell`](../cell/struct.refcell), which provides *interior mutability*: a method to achieve mutability through a shared reference. [`RefCell`](../cell/struct.refcell) enforces Rust’s borrowing rules at runtime. ``` use std::rc::Rc; use std::rc::Weak; use std::cell::RefCell; struct Owner { name: String, gadgets: RefCell<Vec<Weak<Gadget>>>, // ...other fields } struct Gadget { id: i32, owner: Rc<Owner>, // ...other fields } fn main() { // Create a reference-counted `Owner`. Note that we've put the `Owner`'s // vector of `Gadget`s inside a `RefCell` so that we can mutate it through // a shared reference. let gadget_owner: Rc<Owner> = Rc::new( Owner { name: "Gadget Man".to_string(), gadgets: RefCell::new(vec![]), } ); // Create `Gadget`s belonging to `gadget_owner`, as before. let gadget1 = Rc::new( Gadget { id: 1, owner: Rc::clone(&gadget_owner), } ); let gadget2 = Rc::new( Gadget { id: 2, owner: Rc::clone(&gadget_owner), } ); // Add the `Gadget`s to their `Owner`. { let mut gadgets = gadget_owner.gadgets.borrow_mut(); gadgets.push(Rc::downgrade(&gadget1)); gadgets.push(Rc::downgrade(&gadget2)); // `RefCell` dynamic borrow ends here. } // Iterate over our `Gadget`s, printing their details out. for gadget_weak in gadget_owner.gadgets.borrow().iter() { // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't // guarantee the allocation still exists, we need to call // `upgrade`, which returns an `Option<Rc<Gadget>>`. // // In this case we know the allocation still exists, so we simply // `unwrap` the `Option`. In a more complicated program, you might // need graceful error handling for a `None` result. let gadget = gadget_weak.upgrade().unwrap(); println!("Gadget {} owned by {}", gadget.id, gadget.owner.name); } // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2` // are destroyed. There are now no strong (`Rc`) pointers to the // gadgets, so they are destroyed. This zeroes the reference count on // Gadget Man, so he gets destroyed as well. } ``` Structs ------- [Rc](struct.rc "std::rc::Rc struct") A single-threaded reference-counting pointer. ‘Rc’ stands for ‘Reference Counted’. [Weak](struct.weak "std::rc::Weak struct") `Weak` is a version of [`Rc`](struct.rc "Rc") that holds a non-owning reference to the managed allocation. The allocation is accessed by calling [`upgrade`](struct.weak#method.upgrade) on the `Weak` pointer, which returns an `[Option](../option/enum.option "Option")<[Rc](struct.rc "Rc")<T>>`. rust Struct std::rc::Weak Struct std::rc::Weak ==================== ``` pub struct Weak<T>where    T: ?Sized,{ /* private fields */ } ``` `Weak` is a version of [`Rc`](struct.rc "Rc") that holds a non-owning reference to the managed allocation. The allocation is accessed by calling [`upgrade`](struct.weak#method.upgrade) on the `Weak` pointer, which returns an `[Option](../option/enum.option "Option")<[Rc](struct.rc "Rc")<T>>`. Since a `Weak` reference does not count towards ownership, it will not prevent the value stored in the allocation from being dropped, and `Weak` itself makes no guarantees about the value still being present. Thus it may return [`None`](../option/enum.option#variant.None "None") when [`upgrade`](struct.weak#method.upgrade)d. Note however that a `Weak` reference *does* prevent the allocation itself (the backing store) from being deallocated. A `Weak` pointer is useful for keeping a temporary reference to the allocation managed by [`Rc`](struct.rc "Rc") without preventing its inner value from being dropped. It is also used to prevent circular references between [`Rc`](struct.rc "Rc") pointers, since mutual owning references would never allow either [`Rc`](struct.rc "Rc") to be dropped. For example, a tree could have strong [`Rc`](struct.rc "Rc") pointers from parent nodes to children, and `Weak` pointers from children back to their parents. The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`](struct.rc#method.downgrade "Rc::downgrade"). Implementations --------------- [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2167)### impl<T> Weak<T> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2184)1.10.0 (const: [unstable](https://github.com/rust-lang/rust/issues/95091 "Tracking issue for const_weak_new")) · #### pub fn new() -> Weak<T> Constructs a new `Weak<T>`, without allocating any memory. Calling [`upgrade`](struct.weak#method.upgrade) on the return value always gives [`None`](../option/enum.option#variant.None "None"). ##### Examples ``` use std::rc::Weak; let empty: Weak<i64> = Weak::new(); assert!(empty.upgrade().is_none()); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2200)### impl<T> Weak<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2228)1.45.0 · #### pub fn as\_ptr(&self) -> \*const T Returns a raw pointer to the object `T` pointed to by this `Weak<T>`. The pointer is valid only if there are some strong references. The pointer may be dangling, unaligned or even [`null`](../ptr/fn.null) otherwise. ##### Examples ``` use std::rc::Rc; use std::ptr; let strong = Rc::new("hello".to_owned()); let weak = Rc::downgrade(&strong); // Both point to the same object assert!(ptr::eq(&*strong, weak.as_ptr())); // The strong here keeps it alive, so we can still access the object. assert_eq!("hello", unsafe { &*weak.as_ptr() }); drop(strong); // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to // undefined behaviour. // assert_eq!("hello", unsafe { &*weak.as_ptr() }); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2272)1.45.0 · #### pub fn into\_raw(self) -> \*const T Consumes the `Weak<T>` and turns it into a raw pointer. This converts the weak pointer into a raw pointer, while still preserving the ownership of one weak reference (the weak count is not modified by this operation). It can be turned back into the `Weak<T>` with [`from_raw`](struct.weak#method.from_raw). The same restrictions of accessing the target of the pointer as with [`as_ptr`](struct.weak#method.as_ptr) apply. ##### Examples ``` use std::rc::{Rc, Weak}; let strong = Rc::new("hello".to_owned()); let weak = Rc::downgrade(&strong); let raw = weak.into_raw(); assert_eq!(1, Rc::weak_count(&strong)); assert_eq!("hello", unsafe { &*raw }); drop(unsafe { Weak::from_raw(raw) }); assert_eq!(0, Rc::weak_count(&strong)); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2321)1.45.0 · #### pub unsafe fn from\_raw(ptr: \*const T) -> Weak<T> Converts a raw pointer previously created by [`into_raw`](struct.weak#method.into_raw) back into `Weak<T>`. This can be used to safely get a strong reference (by calling [`upgrade`](struct.weak#method.upgrade) later) or to deallocate the weak count by dropping the `Weak<T>`. It takes ownership of one weak reference (with the exception of pointers created by [`new`](struct.weak#method.new), as these don’t own anything; the method still works on them). ##### Safety The pointer must have originated from the [`into_raw`](struct.weak#method.into_raw) and must still own its potential weak reference. It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this takes ownership of one weak reference currently represented as a raw pointer (the weak count is not modified by this operation) and therefore it must be paired with a previous call to [`into_raw`](struct.weak#method.into_raw). ##### Examples ``` use std::rc::{Rc, Weak}; let strong = Rc::new("hello".to_owned()); let raw_1 = Rc::downgrade(&strong).into_raw(); let raw_2 = Rc::downgrade(&strong).into_raw(); assert_eq!(2, Rc::weak_count(&strong)); assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap()); assert_eq!(1, Rc::weak_count(&strong)); drop(strong); // Decrement the last weak count. assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none()); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2366)#### pub fn upgrade(&self) -> Option<Rc<T>> Attempts to upgrade the `Weak` pointer to an [`Rc`](struct.rc "Rc"), delaying dropping of the inner value if successful. Returns [`None`](../option/enum.option#variant.None "None") if the inner value has since been dropped. ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); let weak_five = Rc::downgrade(&five); let strong_five: Option<Rc<_>> = weak_five.upgrade(); assert!(strong_five.is_some()); // Destroy all strong pointers. drop(strong_five); drop(five); assert!(weak_five.upgrade().is_none()); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2384)1.41.0 · #### pub fn strong\_count(&self) -> usize Gets the number of strong (`Rc`) pointers pointing to this allocation. If `self` was created using [`Weak::new`](struct.weak#method.new "Weak::new"), this will return 0. [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2393)1.41.0 · #### pub fn weak\_count(&self) -> usize Gets the number of `Weak` pointers pointing to this allocation. If no strong pointers remain, this will return zero. [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2464)1.39.0 · #### pub fn ptr\_eq(&self, other: &Weak<T>) -> bool Returns `true` if the two `Weak`s point to the same allocation (similar to [`ptr::eq`](../ptr/fn.eq "ptr::eq")), or if both don’t point to any allocation (because they were created with `Weak::new()`). ##### Notes Since this compares pointers it means that `Weak::new()` will equal each other, even though they don’t point to any allocation. ##### Examples ``` use std::rc::Rc; let first_rc = Rc::new(5); let first = Rc::downgrade(&first_rc); let second = Rc::downgrade(&first_rc); assert!(first.ptr_eq(&second)); let third_rc = Rc::new(5); let third = Rc::downgrade(&third_rc); assert!(!first.ptr_eq(&third)); ``` Comparing `Weak::new`. ``` use std::rc::{Rc, Weak}; let first = Weak::new(); let second = Weak::new(); assert!(first.ptr_eq(&second)); let third_rc = Rc::new(()); let third = Rc::downgrade(&third_rc); assert!(!first.ptr_eq(&third)); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2510)### impl<T> Clone for Weak<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2523)#### fn clone(&self) -> Weak<T> Makes a clone of the `Weak` pointer that points to the same allocation. ##### Examples ``` use std::rc::{Rc, Weak}; let weak_five = Rc::downgrade(&Rc::new(5)); let _ = Weak::clone(&weak_five); ``` [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2532)### impl<T> Debug for Weak<T>where T: [Debug](../fmt/trait.debug "trait std::fmt::Debug") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2533)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2539)1.10.0 · ### impl<T> Default for Weak<T> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2553)#### fn default() -> Weak<T> Constructs a new `Weak<T>`, without allocating any memory. Calling [`upgrade`](struct.weak#method.upgrade) on the return value always gives [`None`](../option/enum.option#variant.None "None"). ##### Examples ``` use std::rc::Weak; let empty: Weak<i64> = Default::default(); assert!(empty.upgrade().is_none()); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2470)### impl<T> Drop for Weak<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2495)#### fn drop(&mut self) Drops the `Weak` pointer. ##### Examples ``` use std::rc::{Rc, Weak}; struct Foo; impl Drop for Foo { fn drop(&mut self) { println!("dropped!"); } } let foo = Rc::new(Foo); let weak_foo = Rc::downgrade(&foo); let other_weak_foo = Weak::clone(&weak_foo); drop(weak_foo); // Doesn't print anything drop(foo); // Prints "dropped!" assert!(other_weak_foo.upgrade().is_none()); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2162)### impl<T, U> CoerceUnsized<Weak<U>> for Weak<T>where T: [Unsize](../marker/trait.unsize "trait std::marker::Unsize")<U> + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), U: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2165)### impl<T, U> DispatchFromDyn<Weak<U>> for Weak<T>where T: [Unsize](../marker/trait.unsize "trait std::marker::Unsize")<U> + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), U: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2157)### impl<T> !Send for Weak<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2159)### impl<T> !Sync for Weak<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), Auto Trait Implementations -------------------------- ### impl<T> !RefUnwindSafe for Weak<T> ### impl<T: ?Sized> Unpin for Weak<T> ### impl<T> !UnwindSafe for Weak<T> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::rc::Rc Struct std::rc::Rc ================== ``` pub struct Rc<T>where    T: ?Sized,{ /* private fields */ } ``` A single-threaded reference-counting pointer. ‘Rc’ stands for ‘Reference Counted’. See the [module-level documentation](index) for more details. The inherent methods of `Rc` are all associated functions, which means that you have to call them as e.g., [`Rc::get_mut(&mut value)`](struct.rc#method.get_mut) instead of `value.get_mut()`. This avoids conflicts with methods of the inner type `T`. Implementations --------------- [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#353)### impl<T> Rc<T> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#365)#### pub fn new(value: T) -> Rc<T> Constructs a new `Rc<T>`. ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#431-433)1.60.0 · #### pub fn new\_cyclic<F>(data\_fn: F) -> Rc<T>where F: [FnOnce](../ops/trait.fnonce "trait std::ops::FnOnce")(&[Weak](struct.weak "struct std::rc::Weak")<T>) -> T, Constructs a new `Rc<T>` while giving you a `Weak<T>` to the allocation, to allow you to construct a `T` which holds a weak pointer to itself. Generally, a structure circularly referencing itself, either directly or indirectly, should not hold a strong reference to itself to prevent a memory leak. Using this function, you get access to the weak pointer during the initialization of `T`, before the `Rc<T>` is created, such that you can clone and store it inside the `T`. `new_cyclic` first allocates the managed allocation for the `Rc<T>`, then calls your closure, giving it a `Weak<T>` to this allocation, and only afterwards completes the construction of the `Rc<T>` by placing the `T` returned from your closure into the allocation. Since the new `Rc<T>` is not fully-constructed until `Rc<T>::new_cyclic` returns, calling [`upgrade`](struct.weak#method.upgrade) on the weak reference inside your closure will fail and result in a `None` value. ##### Panics If `data_fn` panics, the panic is propagated to the caller, and the temporary [`Weak<T>`](struct.weak "Weak<T>") is dropped normally. ##### Examples ``` use std::rc::{Rc, Weak}; struct Gadget { me: Weak<Gadget>, } impl Gadget { /// Construct a reference counted Gadget. fn new() -> Rc<Self> { // `me` is a `Weak<Gadget>` pointing at the new allocation of the // `Rc` we're constructing. Rc::new_cyclic(|me| { // Create the actual struct here. Gadget { me: me.clone() } }) } /// Return a reference counted pointer to Self. fn me(&self) -> Rc<Self> { self.me.upgrade().unwrap() } } ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#495)#### pub fn new\_uninit() -> Rc<MaybeUninit<T>> 🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291)) Constructs a new `Rc` with uninitialized contents. ##### Examples ``` #![feature(new_uninit)] #![feature(get_mut_unchecked)] use std::rc::Rc; let mut five = Rc::<u32>::new_uninit(); // Deferred initialization: Rc::get_mut(&mut five).unwrap().write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#528)#### pub fn new\_zeroed() -> Rc<MaybeUninit<T>> 🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291)) Constructs a new `Rc` with uninitialized contents, with the memory being filled with `0` bytes. See [`MaybeUninit::zeroed`](../mem/union.maybeuninit#method.zeroed) for examples of correct and incorrect usage of this method. ##### Examples ``` #![feature(new_uninit)] use std::rc::Rc; let zero = Rc::<u32>::new_zeroed(); let zero = unsafe { zero.assume_init() }; assert_eq!(*zero, 0) ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#550)#### pub fn try\_new(value: T) -> Result<Rc<T>, AllocError> 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838)) Constructs a new `Rc<T>`, returning an error if the allocation fails ##### Examples ``` #![feature(allocator_api)] use std::rc::Rc; let five = Rc::try_new(5); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#585)#### pub fn try\_new\_uninit() -> Result<Rc<MaybeUninit<T>>, AllocError> 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838)) Constructs a new `Rc` with uninitialized contents, returning an error if the allocation fails ##### Examples ``` #![feature(allocator_api, new_uninit)] #![feature(get_mut_unchecked)] use std::rc::Rc; let mut five = Rc::<u32>::try_new_uninit()?; // Deferred initialization: Rc::get_mut(&mut five).unwrap().write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#618)#### pub fn try\_new\_zeroed() -> Result<Rc<MaybeUninit<T>>, AllocError> 🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838)) Constructs a new `Rc` with uninitialized contents, with the memory being filled with `0` bytes, returning an error if the allocation fails See [`MaybeUninit::zeroed`](../mem/union.maybeuninit#method.zeroed) for examples of correct and incorrect usage of this method. ##### Examples ``` #![feature(allocator_api, new_uninit)] use std::rc::Rc; let zero = Rc::<u32>::try_new_zeroed()?; let zero = unsafe { zero.assume_init() }; assert_eq!(*zero, 0); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#632)1.33.0 · #### pub fn pin(value: T) -> Pin<Rc<T>> Notable traits for [Pin](../pin/struct.pin "struct std::pin::Pin")<P> ``` impl<P> Future for Pin<P>where     P: DerefMut,     <P as Deref>::Target: Future, type Output = <<P as Deref>::Target as Future>::Output; ``` Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then `value` will be pinned in memory and unable to be moved. [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#657)1.4.0 · #### pub fn try\_unwrap(this: Rc<T>) -> Result<T, Rc<T>> Returns the inner value, if the `Rc` has exactly one strong reference. Otherwise, an [`Err`](../result/enum.result#variant.Err "Err") is returned with the same `Rc` that was passed in. This will succeed even if there are outstanding weak references. ##### Examples ``` use std::rc::Rc; let x = Rc::new(3); assert_eq!(Rc::try_unwrap(x), Ok(3)); let x = Rc::new(4); let _y = Rc::clone(&x); assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#677)### impl<T> Rc<[T]> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#703)#### pub fn new\_uninit\_slice(len: usize) -> Rc<[MaybeUninit<T>]> 🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291)) Constructs a new reference-counted slice with uninitialized contents. ##### Examples ``` #![feature(new_uninit)] #![feature(get_mut_unchecked)] use std::rc::Rc; let mut values = Rc::<[u32]>::new_uninit_slice(3); // Deferred initialization: let data = Rc::get_mut(&mut values).unwrap(); data[0].write(1); data[1].write(2); data[2].write(3); let values = unsafe { values.assume_init() }; assert_eq!(*values, [1, 2, 3]) ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#730)#### pub fn new\_zeroed\_slice(len: usize) -> Rc<[MaybeUninit<T>]> 🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291)) Constructs a new reference-counted slice with uninitialized contents, with the memory being filled with `0` bytes. See [`MaybeUninit::zeroed`](../mem/union.maybeuninit#method.zeroed) for examples of correct and incorrect usage of this method. ##### Examples ``` #![feature(new_uninit)] use std::rc::Rc; let values = Rc::<[u32]>::new_zeroed_slice(3); let values = unsafe { values.assume_init() }; assert_eq!(*values, [0, 0, 0]) ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#744)### impl<T> Rc<MaybeUninit<T>> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#776)#### pub unsafe fn assume\_init(self) -> Rc<T> 🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291)) Converts to `Rc<T>`. ##### Safety As with [`MaybeUninit::assume_init`](../mem/union.maybeuninit#method.assume_init), it is up to the caller to guarantee that the inner value really is in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior. ##### Examples ``` #![feature(new_uninit)] #![feature(get_mut_unchecked)] use std::rc::Rc; let mut five = Rc::<u32>::new_uninit(); // Deferred initialization: Rc::get_mut(&mut five).unwrap().write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#781)### impl<T> Rc<[MaybeUninit<T>]> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#816)#### pub unsafe fn assume\_init(self) -> Rc<[T]> 🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291)) Converts to `Rc<[T]>`. ##### Safety As with [`MaybeUninit::assume_init`](../mem/union.maybeuninit#method.assume_init), it is up to the caller to guarantee that the inner value really is in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior. ##### Examples ``` #![feature(new_uninit)] #![feature(get_mut_unchecked)] use std::rc::Rc; let mut values = Rc::<[u32]>::new_uninit_slice(3); // Deferred initialization: let data = Rc::get_mut(&mut values).unwrap(); data[0].write(1); data[1].write(2); data[2].write(3); let values = unsafe { values.assume_init() }; assert_eq!(*values, [1, 2, 3]) ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#821)### impl<T> Rc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#837)1.17.0 · #### pub fn into\_raw(this: Rc<T>) -> \*const T Consumes the `Rc`, returning the wrapped pointer. To avoid a memory leak the pointer must be converted back to an `Rc` using [`Rc::from_raw`](struct.rc#method.from_raw "Rc::from_raw"). ##### Examples ``` use std::rc::Rc; let x = Rc::new("hello".to_owned()); let x_ptr = Rc::into_raw(x); assert_eq!(unsafe { &*x_ptr }, "hello"); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#860)1.45.0 · #### pub fn as\_ptr(this: &Rc<T>) -> \*const T Provides a raw pointer to the data. The counts are not affected in any way and the `Rc` is not consumed. The pointer is valid for as long there are strong counts in the `Rc`. ##### Examples ``` use std::rc::Rc; let x = Rc::new("hello".to_owned()); let y = Rc::clone(&x); let x_ptr = Rc::as_ptr(&x); assert_eq!(x_ptr, Rc::as_ptr(&y)); assert_eq!(unsafe { &*x_ptr }, "hello"); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#906)1.17.0 · #### pub unsafe fn from\_raw(ptr: \*const T) -> Rc<T> Constructs an `Rc<T>` from a raw pointer. The raw pointer must have been previously returned by a call to [`Rc<U>::into_raw`](struct.rc#method.into_raw) where `U` must have the same size and alignment as `T`. This is trivially true if `U` is `T`. Note that if `U` is not `T` but has the same size and alignment, this is basically like transmuting references of different types. See [`mem::transmute`](../mem/fn.transmute "mem::transmute") for more information on what restrictions apply in this case. The user of `from_raw` has to make sure a specific value of `T` is only dropped once. This function is unsafe because improper use may lead to memory unsafety, even if the returned `Rc<T>` is never accessed. ##### Examples ``` use std::rc::Rc; let x = Rc::new("hello".to_owned()); let x_ptr = Rc::into_raw(x); unsafe { // Convert back to an `Rc` to prevent leak. let x = Rc::from_raw(x_ptr); assert_eq!(&*x, "hello"); // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe. } // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling! ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#929)1.4.0 · #### pub fn downgrade(this: &Rc<T>) -> Weak<T> Creates a new [`Weak`](struct.weak "Weak") pointer to this allocation. ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); let weak_five = Rc::downgrade(&five); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#950)1.15.0 · #### pub fn weak\_count(this: &Rc<T>) -> usize Gets the number of [`Weak`](struct.weak "Weak") pointers to this allocation. ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); let _weak_five = Rc::downgrade(&five); assert_eq!(1, Rc::weak_count(&five)); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#968)1.15.0 · #### pub fn strong\_count(this: &Rc<T>) -> usize Gets the number of strong (`Rc`) pointers to this allocation. ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); let _also_five = Rc::clone(&five); assert_eq!(2, Rc::strong_count(&five)); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#998)1.53.0 · #### pub unsafe fn increment\_strong\_count(ptr: \*const T) Increments the strong reference count on the `Rc<T>` associated with the provided pointer by one. ##### Safety The pointer must have been obtained through `Rc::into_raw`, and the associated `Rc` instance must be valid (i.e. the strong count must be at least 1) for the duration of this method. ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); unsafe { let ptr = Rc::into_raw(five); Rc::increment_strong_count(ptr); let five = Rc::from_raw(ptr); assert_eq!(2, Rc::strong_count(&five)); } ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1035)1.53.0 · #### pub unsafe fn decrement\_strong\_count(ptr: \*const T) Decrements the strong reference count on the `Rc<T>` associated with the provided pointer by one. ##### Safety The pointer must have been obtained through `Rc::into_raw`, and the associated `Rc` instance must be valid (i.e. the strong count must be at least 1) when invoking this method. This method can be used to release the final `Rc` and backing storage, but **should not** be called after the final `Rc` has been released. ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); unsafe { let ptr = Rc::into_raw(five); Rc::increment_strong_count(ptr); let five = Rc::from_raw(ptr); assert_eq!(2, Rc::strong_count(&five)); Rc::decrement_strong_count(ptr); assert_eq!(1, Rc::strong_count(&five)); } ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1072)1.4.0 · #### pub fn get\_mut(this: &mut Rc<T>) -> Option<&mut T> Returns a mutable reference into the given `Rc`, if there are no other `Rc` or [`Weak`](struct.weak "Weak") pointers to the same allocation. Returns [`None`](../option/enum.option#variant.None "None") otherwise, because it is not safe to mutate a shared value. See also [`make_mut`](struct.rc#method.make_mut), which will [`clone`](../clone/trait.clone#tymethod.clone) the inner value when there are other `Rc` pointers. ##### Examples ``` use std::rc::Rc; let mut x = Rc::new(3); *Rc::get_mut(&mut x).unwrap() = 4; assert_eq!(*x, 4); let _y = Rc::clone(&x); assert!(Rc::get_mut(&mut x).is_none()); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1105)#### pub unsafe fn get\_mut\_unchecked(this: &mut Rc<T>) -> &mut T 🔬This is a nightly-only experimental API. (`get_mut_unchecked` [#63292](https://github.com/rust-lang/rust/issues/63292)) Returns a mutable reference into the given `Rc`, without any check. See also [`get_mut`](struct.rc#method.get_mut), which is safe and does appropriate checks. ##### Safety Any other `Rc` or [`Weak`](struct.weak "Weak") pointers to the same allocation must not be dereferenced for the duration of the returned borrow. This is trivially the case if no such pointers exist, for example immediately after `Rc::new`. ##### Examples ``` #![feature(get_mut_unchecked)] use std::rc::Rc; let mut x = Rc::new(String::new()); unsafe { Rc::get_mut_unchecked(&mut x).push_str("foo") } assert_eq!(*x, "foo"); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1128)1.17.0 · #### pub fn ptr\_eq(this: &Rc<T>, other: &Rc<T>) -> bool Returns `true` if the two `Rc`s point to the same allocation (in a vein similar to [`ptr::eq`](../ptr/fn.eq "ptr::eq")). ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); let same_five = Rc::clone(&five); let other_five = Rc::new(5); assert!(Rc::ptr_eq(&five, &same_five)); assert!(!Rc::ptr_eq(&five, &other_five)); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1133)### impl<T> Rc<T>where T: [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1187)1.4.0 · #### pub fn make\_mut(this: &mut Rc<T>) -> &mut T Makes a mutable reference into the given `Rc`. If there are other `Rc` pointers to the same allocation, then `make_mut` will [`clone`](../clone/trait.clone#tymethod.clone) the inner value to a new allocation to ensure unique ownership. This is also referred to as clone-on-write. However, if there are no other `Rc` pointers to this allocation, but some [`Weak`](struct.weak "Weak") pointers, then the [`Weak`](struct.weak "Weak") pointers will be disassociated and the inner value will not be cloned. See also [`get_mut`](struct.rc#method.get_mut), which will fail rather than cloning the inner value or disassociating [`Weak`](struct.weak "Weak") pointers. ##### Examples ``` use std::rc::Rc; let mut data = Rc::new(5); *Rc::make_mut(&mut data) += 1; // Won't clone anything let mut other_data = Rc::clone(&data); // Won't clone inner data *Rc::make_mut(&mut data) += 1; // Clones inner data *Rc::make_mut(&mut data) += 1; // Won't clone anything *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything // Now `data` and `other_data` point to different allocations. assert_eq!(*data, 8); assert_eq!(*other_data, 12); ``` [`Weak`](struct.weak "Weak") pointers will be disassociated: ``` use std::rc::Rc; let mut data = Rc::new(75); let weak = Rc::downgrade(&data); assert!(75 == *data); assert!(75 == *weak.upgrade().unwrap()); *Rc::make_mut(&mut data) += 1; assert!(76 == *data); assert!(weak.upgrade().is_none()); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1250)#### pub fn unwrap\_or\_clone(this: Rc<T>) -> T 🔬This is a nightly-only experimental API. (`arc_unwrap_or_clone` [#93610](https://github.com/rust-lang/rust/issues/93610)) If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the clone. Assuming `rc_t` is of type `Rc<T>`, this function is functionally equivalent to `(*rc_t).clone()`, but will avoid cloning the inner value where possible. ##### Examples ``` #![feature(arc_unwrap_or_clone)] let inner = String::from("test"); let ptr = inner.as_ptr(); let rc = Rc::new(inner); let inner = Rc::unwrap_or_clone(rc); // The inner value was not cloned assert!(ptr::eq(ptr, inner.as_ptr())); let rc = Rc::new(inner); let rc2 = rc.clone(); let inner = Rc::unwrap_or_clone(rc); // Because there were 2 references, we had to clone the inner value. assert!(!ptr::eq(ptr, inner.as_ptr())); // `rc2` is the last reference, so when we unwrap it we get back // the original `String`. let inner = Rc::unwrap_or_clone(rc2); assert!(ptr::eq(ptr, inner.as_ptr())); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1255)### impl Rc<dyn Any + 'static> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1276)1.29.0 · #### pub fn downcast<T>(self) -> Result<Rc<T>, Rc<dyn Any + 'static>>where T: [Any](../any/trait.any "trait std::any::Any"), Attempt to downcast the `Rc<dyn Any>` to a concrete type. ##### Examples ``` use std::any::Any; use std::rc::Rc; fn print_if_string(value: Rc<dyn Any>) { if let Ok(string) = value.downcast::<String>() { println!("String ({}): {}", string.len(), string); } } let my_string = "Hello World".to_string(); print_if_string(Rc::new(my_string)); print_if_string(Rc::new(0i8)); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1316)#### pub unsafe fn downcast\_unchecked<T>(self) -> Rc<T>where T: [Any](../any/trait.any "trait std::any::Any"), 🔬This is a nightly-only experimental API. (`downcast_unchecked` [#90850](https://github.com/rust-lang/rust/issues/90850)) Downcasts the `Rc<dyn Any>` to a concrete type. For a safe alternative see [`downcast`](struct.rc#method.downcast). ##### Examples ``` #![feature(downcast_unchecked)] use std::any::Any; use std::rc::Rc; let x: Rc<dyn Any> = Rc::new(1_usize); unsafe { assert_eq!(*x.downcast_unchecked::<usize>(), 1); } ``` ##### Safety The contained value must be of type `T`. Calling this method with the incorrect type is *undefined behavior*. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2671)1.5.0 · ### impl<T> AsRef<T> for Rc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2672)#### fn as\_ref(&self) -> &T Converts this type into a shared reference of the (usually inferred) input type. [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2664)### impl<T> Borrow<T> for Rc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2665)#### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1574)### impl<T> Clone for Rc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1590)#### fn clone(&self) -> Rc<T> Makes a clone of the `Rc` pointer. This creates another pointer to the same allocation, increasing the strong reference count. ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); let _ = Rc::clone(&five); ``` [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1844)### impl<T> Debug for Rc<T>where T: [Debug](../fmt/trait.debug "trait std::fmt::Debug") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1845)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1600)### impl<T> Default for Rc<T>where T: [Default](../default/trait.default "trait std::default::Default"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1612)#### fn default() -> Rc<T> Creates a new `Rc<T>`, with the `Default` value for `T`. ##### Examples ``` use std::rc::Rc; let x: Rc<i32> = Default::default(); assert_eq!(*x, 0); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1515)### impl<T> Deref for Rc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), #### type Target = T The resulting type after dereferencing. [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1519)#### fn deref(&self) -> &T Dereferences the value. [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1837)### impl<T> Display for Rc<T>where T: [Display](../fmt/trait.display "trait std::fmt::Display") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1838)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt) [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1528)### impl<T> Drop for Rc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1554)#### fn drop(&mut self) Drops the `Rc`. This will decrement the strong reference count. If the strong reference count reaches zero then the only other references (if any) are [`Weak`](struct.weak "Weak"), so we `drop` the inner value. ##### Examples ``` use std::rc::Rc; struct Foo; impl Drop for Foo { fn drop(&mut self) { println!("dropped!"); } } let foo = Rc::new(Foo); let foo2 = Rc::clone(&foo); drop(foo); // Doesn't print anything drop(foo2); // Prints "dropped!" ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1880)1.21.0 · ### impl<T> From<&[T]> for Rc<[T]>where T: [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1892)#### fn from(v: &[T]) -> Rc<[T]> Allocate a reference-counted slice and fill it by cloning `v`’s items. ##### Example ``` let original: &[i32] = &[1, 2, 3]; let shared: Rc<[i32]> = Rc::from(original); assert_eq!(&[1, 2, 3], &shared[..]); ``` [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#900)1.24.0 · ### impl From<&CStr> for Rc<CStr> [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#904)#### fn from(s: &CStr) -> Rc<CStr> Converts a `&CStr` into a `Rc<CStr>`, by copying the contents into a newly allocated [`Rc`](struct.rc "Rc"). [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1067-1074)1.24.0 · ### impl From<&OsStr> for Rc<OsStr> [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1070-1073)#### fn from(s: &OsStr) -> Rc<OsStr> Copies the string into a newly allocated `[Rc](struct.rc "Rc")<[OsStr](../ffi/struct.osstr "OsStr")>`. [source](https://doc.rust-lang.org/src/std/path.rs.html#1823-1830)1.24.0 · ### impl From<&Path> for Rc<Path> [source](https://doc.rust-lang.org/src/std/path.rs.html#1826-1829)#### fn from(s: &Path) -> Rc<Path> Converts a [`Path`](../path/struct.path "Path") into an [`Rc`](struct.rc "Rc") by copying the [`Path`](../path/struct.path "Path") data into a new [`Rc`](struct.rc "Rc") buffer. [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1899)1.21.0 · ### impl From<&str> for Rc<str> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1910)#### fn from(v: &str) -> Rc<str> Allocate a reference-counted string slice and copy `v` into it. ##### Example ``` let shared: Rc<str> = Rc::from("statue"); assert_eq!("statue", &shared[..]); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1937)1.21.0 · ### impl<T> From<Box<T, Global>> for Rc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1949)#### fn from(v: Box<T, Global>) -> Rc<T> Move a boxed object to a new, reference counted, allocation. ##### Example ``` let original: Box<i32> = Box::new(1); let shared: Rc<i32> = Rc::from(original); assert_eq!(1, *shared); ``` [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#889)1.24.0 · ### impl From<CString> for Rc<CStr> [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#893)#### fn from(s: CString) -> Rc<CStr> Converts a [`CString`](../ffi/struct.cstring "CString") into an `[Rc](struct.rc "Rc")<[CStr](../ffi/struct.cstr "CStr")>` by moving the [`CString`](../ffi/struct.cstring "CString") data into a new [`Arc`](../sync/struct.arc "Arc") buffer. [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1981)1.45.0 · ### impl<'a, B> From<Cow<'a, B>> for Rc<B>where B: [ToOwned](../borrow/trait.toowned "trait std::borrow::ToOwned") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [Rc](struct.rc "struct std::rc::Rc")<B>: [From](../convert/trait.from "trait std::convert::From")<[&'a](../primitive.reference) B>, [Rc](struct.rc "struct std::rc::Rc")<B>: [From](../convert/trait.from "trait std::convert::From")<<B as [ToOwned](../borrow/trait.toowned "trait std::borrow::ToOwned")>::[Owned](../borrow/trait.toowned#associatedtype.Owned "type std::borrow::ToOwned::Owned")>, [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1999)#### fn from(cow: Cow<'a, B>) -> Rc<B> Create a reference-counted pointer from a clone-on-write pointer by copying its content. ##### Example ``` let cow: Cow<str> = Cow::Borrowed("eggplant"); let shared: Rc<str> = Rc::from(cow); assert_eq!("eggplant", &shared[..]); ``` [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1056-1064)1.24.0 · ### impl From<OsString> for Rc<OsStr> [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1060-1063)#### fn from(s: OsString) -> Rc<OsStr> Converts an [`OsString`](../ffi/struct.osstring "OsString") into an `[Rc](struct.rc "Rc")<[OsStr](../ffi/struct.osstr "OsStr")>` by moving the [`OsString`](../ffi/struct.osstring "OsString") data into a new [`Rc`](struct.rc "Rc") buffer. [source](https://doc.rust-lang.org/src/std/path.rs.html#1812-1820)1.24.0 · ### impl From<PathBuf> for Rc<Path> [source](https://doc.rust-lang.org/src/std/path.rs.html#1816-1819)#### fn from(s: PathBuf) -> Rc<Path> Converts a [`PathBuf`](../path/struct.pathbuf "PathBuf") into an `[Rc](struct.rc "Rc")<[Path](../path/struct.path "Path")>` by moving the [`PathBuf`](../path/struct.pathbuf "PathBuf") data into a new [`Rc`](struct.rc "Rc") buffer. [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2008)1.62.0 · ### impl From<Rc<str>> for Rc<[u8]> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2020)#### fn from(rc: Rc<str>) -> Rc<[u8]> Converts a reference-counted string slice into a byte slice. ##### Example ``` let string: Rc<str> = Rc::from("eggplant"); let bytes: Rc<[u8]> = Rc::from(string); assert_eq!("eggplant".as_bytes(), bytes.as_ref()); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1918)1.21.0 · ### impl From<String> for Rc<str> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1930)#### fn from(v: String) -> Rc<str> Allocate a reference-counted string slice and copy `v` into it. ##### Example ``` let original: String = "statue".to_owned(); let shared: Rc<str> = Rc::from(original); assert_eq!("statue", &shared[..]); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1859)1.6.0 · ### impl<T> From<T> for Rc<T> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1873)#### fn from(t: T) -> Rc<T> Converts a generic type `T` into an `Rc<T>` The conversion allocates on the heap and moves `t` from the stack into it. ##### Example ``` let x = 5; let rc = Rc::new(5); assert_eq!(Rc::from(x), rc); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1956)1.21.0 · ### impl<T> From<Vec<T, Global>> for Rc<[T]> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1968)#### fn from(v: Vec<T, Global>) -> Rc<[T]> Allocate a reference-counted slice and move `v`’s items into it. ##### Example ``` let original: Box<Vec<i32>> = Box::new(vec![1, 2, 3]); let shared: Rc<Vec<i32>> = Rc::from(original); assert_eq!(vec![1, 2, 3], *shared); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2041)1.37.0 · ### impl<T> FromIterator<T> for Rc<[T]> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2080)#### fn from\_iter<I>(iter: I) -> Rc<[T]>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = T>, Takes each element in the `Iterator` and collects it into an `Rc<[T]>`. ##### Performance characteristics ###### [The general case](#the-general-case) In the general case, collecting into `Rc<[T]>` is done by first collecting into a `Vec<T>`. That is, when writing the following: ``` let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect(); ``` this behaves as if we wrote: ``` let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0) .collect::<Vec<_>>() // The first set of allocations happens here. .into(); // A second allocation for `Rc<[T]>` happens here. ``` This will allocate as many times as needed for constructing the `Vec<T>` and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`. ###### [Iterators of known length](#iterators-of-known-length) When your `Iterator` implements `TrustedLen` and is of an exact size, a single allocation will be made for the `Rc<[T]>`. For example: ``` let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here. ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1830)### impl<T> Hash for Rc<T>where T: [Hash](../hash/trait.hash "trait std::hash::Hash") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1831)#### fn hash<H>(&self, state: &mut H)where H: [Hasher](../hash/trait.hasher "trait std::hash::Hasher"), Feeds this value into the given [`Hasher`](../hash/trait.hasher "Hasher"). [Read more](../hash/trait.hash#tymethod.hash) [source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0 · #### fn hash\_slice<H>(data: &[Self], state: &mut H)where H: [Hasher](../hash/trait.hasher "trait std::hash::Hasher"), Feeds a slice of this type into the given [`Hasher`](../hash/trait.hasher "Hasher"). [Read more](../hash/trait.hash#method.hash_slice) [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1808)### impl<T> Ord for Rc<T>where T: [Ord](../cmp/trait.ord "trait std::cmp::Ord") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1824)#### fn cmp(&self, other: &Rc<T>) -> Ordering Comparison for two `Rc`s. The two are compared by calling `cmp()` on their inner values. ##### Examples ``` use std::rc::Rc; use std::cmp::Ordering; let five = Rc::new(5); assert_eq!(Ordering::Less, five.cmp(&Rc::new(6))); ``` [source](https://doc.rust-lang.org/src/core/cmp.rs.html#804-807)1.21.0 · #### fn max(self, other: Self) -> Self Compares and returns the maximum of two values. [Read more](../cmp/trait.ord#method.max) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#831-834)1.21.0 · #### fn min(self, other: Self) -> Self Compares and returns the minimum of two values. [Read more](../cmp/trait.ord#method.min) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#863-867)1.50.0 · #### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<Self>, Restrict a value to a certain interval. [Read more](../cmp/trait.ord#method.clamp) [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1663)### impl<T> PartialEq<Rc<T>> for Rc<T>where T: [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<T> + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1683)#### fn eq(&self, other: &Rc<T>) -> bool Equality for two `Rc`s. Two `Rc`s are equal if their inner values are equal, even if they are stored in different allocation. If `T` also implements `Eq` (implying reflexivity of equality), two `Rc`s that point to the same allocation are always equal. ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); assert!(five == Rc::new(5)); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1705)#### fn ne(&self, other: &Rc<T>) -> bool Inequality for two `Rc`s. Two `Rc`s are unequal if their inner values are unequal. If `T` also implements `Eq` (implying reflexivity of equality), two `Rc`s that point to the same allocation are never unequal. ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); assert!(five != Rc::new(6)); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1714)### impl<T> PartialOrd<Rc<T>> for Rc<T>where T: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<T> + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1730)#### fn partial\_cmp(&self, other: &Rc<T>) -> Option<Ordering> Partial comparison for two `Rc`s. The two are compared by calling `partial_cmp()` on their inner values. ##### Examples ``` use std::rc::Rc; use std::cmp::Ordering; let five = Rc::new(5); assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6))); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1748)#### fn lt(&self, other: &Rc<T>) -> bool Less-than comparison for two `Rc`s. The two are compared by calling `<` on their inner values. ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); assert!(five < Rc::new(6)); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1766)#### fn le(&self, other: &Rc<T>) -> bool ‘Less than or equal to’ comparison for two `Rc`s. The two are compared by calling `<=` on their inner values. ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); assert!(five <= Rc::new(5)); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1784)#### fn gt(&self, other: &Rc<T>) -> bool Greater-than comparison for two `Rc`s. The two are compared by calling `>` on their inner values. ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); assert!(five > Rc::new(4)); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1802)#### fn ge(&self, other: &Rc<T>) -> bool ‘Greater than or equal to’ comparison for two `Rc`s. The two are compared by calling `>=` on their inner values. ##### Examples ``` use std::rc::Rc; let five = Rc::new(5); assert!(five >= Rc::new(5)); ``` [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1851)### impl<T> Pointer for Rc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1852)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2027)1.43.0 · ### impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]> #### type Error = Rc<[T]> The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2030)#### fn try\_from( boxed\_slice: Rc<[T]>) -> Result<Rc<[T; N]>, <Rc<[T; N]> as TryFrom<Rc<[T]>>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#331)### impl<T, U> CoerceUnsized<Rc<U>> for Rc<T>where T: [Unsize](../marker/trait.unsize "trait std::marker::Unsize")<U> + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), U: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#334)### impl<T, U> DispatchFromDyn<Rc<U>> for Rc<T>where T: [Unsize](../marker/trait.unsize "trait std::marker::Unsize")<U> + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), U: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1711)### impl<T> Eq for Rc<T>where T: [Eq](../cmp/trait.eq "trait std::cmp::Eq") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#328)1.58.0 · ### impl<T> RefUnwindSafe for Rc<T>where T: [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#315)### impl<T> !Send for Rc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#323)### impl<T> !Sync for Rc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2678)1.33.0 · ### impl<T> Unpin for Rc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#326)1.9.0 · ### impl<T> UnwindSafe for Rc<T>where T: [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#577)### impl<T> From<!> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#578)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: !) -> T Converts to this type from the input type. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2500)### impl<T> ToString for Twhere T: [Display](../fmt/trait.display "trait std::fmt::Display") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2506)#### default fn to\_string(&self) -> String Converts the given value to a `String`. [Read more](../string/trait.tostring#tymethod.to_string) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Module std::error Module std::error ================= Interfaces for working with Errors. Error Handling In Rust ---------------------- The Rust language provides two complementary systems for constructing / representing, reporting, propagating, reacting to, and discarding errors. These responsibilities are collectively known as “error handling.” The components of the first system, the panic runtime and interfaces, are most commonly used to represent bugs that have been detected in your program. The components of the second system, `Result`, the error traits, and user defined types, are used to represent anticipated runtime failure modes of your program. ### The Panic Interfaces The following are the primary interfaces of the panic system and the responsibilities they cover: * [`panic!`](../macro.panic "panic!") and [`panic_any`](../panic/fn.panic_any) (Constructing, Propagated automatically) * [`PanicInfo`](../panic/struct.panicinfo) (Reporting) * [`set_hook`](../panic/fn.set_hook), [`take_hook`](../panic/fn.take_hook), and [`#[panic_handler]`](https://doc.rust-lang.org/nomicon/panic-handler.html) (Reporting) * [`catch_unwind`](../panic/fn.catch_unwind) and [`resume_unwind`](../panic/fn.resume_unwind) (Discarding, Propagating) The following are the primary interfaces of the error system and the responsibilities they cover: * [`Result`](../result/enum.result "Result") (Propagating, Reacting) * The [`Error`](trait.error "Error") trait (Reporting) * User defined types (Constructing / Representing) * [`match`](../keyword.match) and [`downcast`](trait.error) (Reacting) * The question mark operator ([`?`](../result/index#the-question-mark-operator-)) (Propagating) * The partially stable [`Try`](../ops/trait.try) traits (Propagating, Constructing) * [`Termination`](../process/trait.termination) (Reporting) ### Converting Errors into Panics The panic and error systems are not entirely distinct. Often times errors that are anticipated runtime failures in an API might instead represent bugs to a caller. For these situations the standard library provides APIs for constructing panics with an `Error` as it’s source. * [`Result::unwrap`](../result/enum.result#method.unwrap "Result::unwrap") * [`Result::expect`](../result/enum.result#method.expect "Result::expect") These functions are equivalent, they either return the inner value if the `Result` is `Ok` or panic if the `Result` is `Err` printing the inner error as the source. The only difference between them is that with `expect` you provide a panic error message to be printed alongside the source, whereas `unwrap` has a default message indicating only that you unwraped an `Err`. Of the two, `expect` is generally preferred since its `msg` field allows you to convey your intent and assumptions which makes tracking down the source of a panic easier. `unwrap` on the other hand can still be a good fit in situations where you can trivially show that a piece of code will never panic, such as `"127.0.0.1".parse::<std::net::IpAddr>().unwrap()` or early prototyping. Common Message Styles --------------------- There are two common styles for how people word `expect` messages. Using the message to present information to users encountering a panic (“expect as error message”) or using the message to present information to developers debugging the panic (“expect as precondition”). In the former case the expect message is used to describe the error that has occurred which is considered a bug. Consider the following example: ⓘ ``` // Read environment variable, panic if it is not present let path = std::env::var("IMPORTANT_PATH").unwrap(); ``` In the “expect as error message” style we would use expect to describe that the environment variable was not set when it should have been: ⓘ ``` let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` is not set"); ``` In the “expect as precondition” style, we would instead describe the reason we *expect* the `Result` should be `Ok`. With this style we would prefer to write: ⓘ ``` let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` The “expect as error message” style does not work as well with the default output of the std panic hooks, and often ends up repeating information that is already communicated by the source error being unwrapped: ``` thread 'main' panicked at 'env variable `IMPORTANT_PATH` is not set: NotPresent', src/main.rs:4:6 ``` In this example we end up mentioning that an env variable is not set, followed by our source message that says the env is not present, the only additional information we’re communicating is the name of the environment variable being checked. The “expect as precondition” style instead focuses on source code readability, making it easier to understand what must have gone wrong in situations where panics are being used to represent bugs exclusively. Also, by framing our expect in terms of what “SHOULD” have happened to prevent the source error, we end up introducing new information that is independent from our source error. ``` thread 'main' panicked at 'env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`: NotPresent', src/main.rs:4:6 ``` In this example we are communicating not only the name of the environment variable that should have been set, but also an explanation for why it should have been set, and we let the source error display as a clear contradiction to our expectation. **Hint**: If you’re having trouble remembering how to phrase expect-as-precondition style error messages remember to focus on the word “should” as in “env variable should be set by blah” or “the given binary should be available and executable by the current user”. Structs ------- [Report](struct.report "std::error::Report struct")Experimental An error reporter that prints an error and its sources. Traits ------ [Error](trait.error "std::error::Error trait") `Error` is a trait representing the basic expectations for error values, i.e., values of type `E` in [`Result<T, E>`](../result/enum.result "Result<T, E>"). rust Trait std::error::Error Trait std::error::Error ======================= ``` pub trait Error: Debug + Display { fn source(&self) -> Option<&(dyn Error + 'static)> { ... } fn description(&self) -> &str { ... } fn cause(&self) -> Option<&dyn Error> { ... } fn provide(&'a self, demand: &mut Demand<'a>) { ... } } ``` `Error` is a trait representing the basic expectations for error values, i.e., values of type `E` in [`Result<T, E>`](../result/enum.result "Result<T, E>"). Errors must describe themselves through the [`Display`](../fmt/trait.display "Display") and [`Debug`](../fmt/trait.debug "Debug") traits. Error messages are typically concise lowercase sentences without trailing punctuation: ``` let err = "NaN".parse::<u32>().unwrap_err(); assert_eq!(err.to_string(), "invalid digit found in string"); ``` Errors may provide cause information. [`Error::source()`](trait.error#method.source "Error::source()") is generally used when errors cross “abstraction boundaries”. If one module must report an error that is caused by an error from a lower-level module, it can allow accessing that error via [`Error::source()`](trait.error#method.source "Error::source()"). This makes it possible for the high-level module to provide its own errors while also revealing some of the implementation for debugging. Provided Methods ---------------- [source](https://doc.rust-lang.org/src/core/error.rs.html#83)1.30.0 · #### fn source(&self) -> Option<&(dyn Error + 'static)> The lower-level source of this error, if any. ##### Examples ``` use std::error::Error; use std::fmt; #[derive(Debug)] struct SuperError { source: SuperErrorSideKick, } impl fmt::Display for SuperError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SuperError is here!") } } impl Error for SuperError { fn source(&self) -> Option<&(dyn Error + 'static)> { Some(&self.source) } } #[derive(Debug)] struct SuperErrorSideKick; impl fmt::Display for SuperErrorSideKick { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SuperErrorSideKick is here!") } } impl Error for SuperErrorSideKick {} fn get_super_error() -> Result<(), SuperError> { Err(SuperError { source: SuperErrorSideKick }) } fn main() { match get_super_error() { Err(e) => { println!("Error: {e}"); println!("Caused by: {}", e.source().unwrap()); } _ => println!("No error"), } } ``` [source](https://doc.rust-lang.org/src/core/error.rs.html#109)#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to\_string() ``` if let Err(e) = "xc".parse::<u32>() { // Print `e` itself, no need for description(). eprintln!("Error: {e}"); } ``` [source](https://doc.rust-lang.org/src/core/error.rs.html#119)#### fn cause(&self) -> Option<&dyn Error> 👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting [source](https://doc.rust-lang.org/src/core/error.rs.html#193)#### fn provide(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301)) Provides type based access to context intended for error reports. Used in conjunction with [`Demand::provide_value`](../any/struct.demand#method.provide_value "Demand::provide_value") and [`Demand::provide_ref`](../any/struct.demand#method.provide_ref "Demand::provide_ref") to extract references to member variables from `dyn Error` trait objects. ##### Example ``` #![feature(provide_any)] #![feature(error_generic_member_access)] use core::fmt; use core::any::Demand; #[derive(Debug)] struct MyBacktrace { // ... } impl MyBacktrace { fn new() -> MyBacktrace { // ... } } #[derive(Debug)] struct SourceError { // ... } impl fmt::Display for SourceError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Example Source Error") } } impl std::error::Error for SourceError {} #[derive(Debug)] struct Error { source: SourceError, backtrace: MyBacktrace, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Example Error") } } impl std::error::Error for Error { fn provide<'a>(&'a self, demand: &mut Demand<'a>) { demand .provide_ref::<MyBacktrace>(&self.backtrace) .provide_ref::<dyn std::error::Error + 'static>(&self.source); } } fn main() { let backtrace = MyBacktrace::new(); let source = SourceError {}; let error = Error { source, backtrace }; let dyn_error = &error as &dyn std::error::Error; let backtrace_ref = dyn_error.request_ref::<MyBacktrace>().unwrap(); assert!(core::ptr::eq(&error.backtrace, backtrace_ref)); } ``` Implementations --------------- [source](https://doc.rust-lang.org/src/core/error.rs.html#217)### impl<'a> dyn Error + 'a [source](https://doc.rust-lang.org/src/core/error.rs.html#220)#### pub fn request\_ref<T>(&'a self) -> Option<&'a T>where T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301)) Request a reference of type `T` as context about this error. [source](https://doc.rust-lang.org/src/core/error.rs.html#226)#### pub fn request\_value<T>(&'a self) -> Option<T>where T: 'static, 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301)) Request a value of type `T` as context about this error. [source](https://doc.rust-lang.org/src/core/error.rs.html#232)### impl dyn Error + 'static [source](https://doc.rust-lang.org/src/core/error.rs.html#236)1.3.0 · #### pub fn is<T>(&self) -> boolwhere T: 'static + [Error](trait.error "trait std::error::Error"), Returns `true` if the inner type is the same as `T`. [source](https://doc.rust-lang.org/src/core/error.rs.html#251)1.3.0 · #### pub fn downcast\_ref<T>(&self) -> Option<&T>where T: 'static + [Error](trait.error "trait std::error::Error"), Returns some reference to the inner value if it is of type `T`, or `None` if it isn’t. [source](https://doc.rust-lang.org/src/core/error.rs.html#264)1.3.0 · #### pub fn downcast\_mut<T>(&mut self) -> Option<&mut T>where T: 'static + [Error](trait.error "trait std::error::Error"), Returns some mutable reference to the inner value if it is of type `T`, or `None` if it isn’t. [source](https://doc.rust-lang.org/src/core/error.rs.html#274)### impl dyn Error + Send + 'static [source](https://doc.rust-lang.org/src/core/error.rs.html#278)1.3.0 · #### pub fn is<T>(&self) -> boolwhere T: 'static + [Error](trait.error "trait std::error::Error"), Forwards to the method defined on the type `dyn Error`. [source](https://doc.rust-lang.org/src/core/error.rs.html#285)1.3.0 · #### pub fn downcast\_ref<T>(&self) -> Option<&T>where T: 'static + [Error](trait.error "trait std::error::Error"), Forwards to the method defined on the type `dyn Error`. [source](https://doc.rust-lang.org/src/core/error.rs.html#292)1.3.0 · #### pub fn downcast\_mut<T>(&mut self) -> Option<&mut T>where T: 'static + [Error](trait.error "trait std::error::Error"), Forwards to the method defined on the type `dyn Error`. [source](https://doc.rust-lang.org/src/core/error.rs.html#298)#### pub fn request\_ref<T>(&self) -> Option<&T>where T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301)) Request a reference of type `T` as context about this error. [source](https://doc.rust-lang.org/src/core/error.rs.html#304)#### pub fn request\_value<T>(&self) -> Option<T>where T: 'static, 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301)) Request a value of type `T` as context about this error. [source](https://doc.rust-lang.org/src/core/error.rs.html#309)### impl dyn Error + Send + Sync + 'static [source](https://doc.rust-lang.org/src/core/error.rs.html#313)1.3.0 · #### pub fn is<T>(&self) -> boolwhere T: 'static + [Error](trait.error "trait std::error::Error"), Forwards to the method defined on the type `dyn Error`. [source](https://doc.rust-lang.org/src/core/error.rs.html#320)1.3.0 · #### pub fn downcast\_ref<T>(&self) -> Option<&T>where T: 'static + [Error](trait.error "trait std::error::Error"), Forwards to the method defined on the type `dyn Error`. [source](https://doc.rust-lang.org/src/core/error.rs.html#327)1.3.0 · #### pub fn downcast\_mut<T>(&mut self) -> Option<&mut T>where T: 'static + [Error](trait.error "trait std::error::Error"), Forwards to the method defined on the type `dyn Error`. [source](https://doc.rust-lang.org/src/core/error.rs.html#333)#### pub fn request\_ref<T>(&self) -> Option<&T>where T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301)) Request a reference of type `T` as context about this error. [source](https://doc.rust-lang.org/src/core/error.rs.html#339)#### pub fn request\_value<T>(&self) -> Option<T>where T: 'static, 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301)) Request a value of type `T` as context about this error. [source](https://doc.rust-lang.org/src/core/error.rs.html#344)### impl dyn Error + 'static [source](https://doc.rust-lang.org/src/core/error.rs.html#398)#### pub fn sources(&self) -> Source<'\_> Notable traits for [Source](https://doc.rust-lang.org/core/error/struct.Source.html "struct core::error::Source")<'a> ``` impl<'a> Iterator for Source<'a> type Item = &'a (dyn Error + 'static); ``` 🔬This is a nightly-only experimental API. (`error_iter` [#58520](https://github.com/rust-lang/rust/issues/58520)) Returns an iterator starting with the current error and continuing with recursively calling [`Error::source`](trait.error#method.source "Error::source"). If you want to omit the current error and only use its sources, use `skip(1)`. ##### Examples ``` #![feature(error_iter)] use std::error::Error; use std::fmt; #[derive(Debug)] struct A; #[derive(Debug)] struct B(Option<Box<dyn Error + 'static>>); impl fmt::Display for A { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "A") } } impl fmt::Display for B { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "B") } } impl Error for A {} impl Error for B { fn source(&self) -> Option<&(dyn Error + 'static)> { self.0.as_ref().map(|e| e.as_ref()) } } let b = B(Some(Box::new(A))); // let err : Box<Error> = b.into(); // or let err = &b as &(dyn Error); let mut iter = err.sources(); assert_eq!("B".to_string(), iter.next().unwrap().to_string()); assert_eq!("A".to_string(), iter.next().unwrap().to_string()); assert!(iter.next().is_none()); assert!(iter.next().is_none()); ``` [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2095)### impl dyn Error + 'static [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2100)1.3.0 · #### pub fn downcast<T>( self: Box<dyn Error + 'static, Global>) -> Result<Box<T, Global>, Box<dyn Error + 'static, Global>>where T: 'static + [Error](trait.error "trait std::error::Error"), Attempts to downcast the box to a concrete type. [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2113)### impl dyn Error + Send + 'static [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2118)1.3.0 · #### pub fn downcast<T>( self: Box<dyn Error + Send + 'static, Global>) -> Result<Box<T, Global>, Box<dyn Error + Send + 'static, Global>>where T: 'static + [Error](trait.error "trait std::error::Error"), Attempts to downcast the box to a concrete type. [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2128)### impl dyn Error + Send + Sync + 'static [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2133)1.3.0 · #### pub fn downcast<T>( self: Box<dyn Error + Send + Sync + 'static, Global>) -> Result<Box<T, Global>, Box<dyn Error + Send + Sync + 'static, Global>>where T: 'static + [Error](trait.error "trait std::error::Error"), Attempts to downcast the box to a concrete type. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2312)1.6.0 · ### impl From<&str> for Box<dyn Error + 'static, Global> [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2327)#### fn from(err: &str) -> Box<dyn Error + 'static, Global> Notable traits for [Box](../boxed/struct.box "struct std::boxed::Box")<I, A> ``` impl<I, A> Iterator for Box<I, A>where     I: Iterator + ?Sized,     A: Allocator, type Item = <I as Iterator>::Item; impl<F, A> Future for Box<F, A>where     F: Future + Unpin + ?Sized,     A: Allocator + 'static, type Output = <F as Future>::Output; impl<R: Read + ?Sized> Read for Box<R> impl<W: Write + ?Sized> Write for Box<W> ``` Converts a [`str`](../primitive.str) into a box of dyn [`Error`](trait.error "Error"). ##### Examples ``` use std::error::Error; use std::mem; let a_str_error = "a str error"; let a_boxed_error = Box::<dyn Error>::from(a_str_error); assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error)) ``` [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2287)### impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a, Global> [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2304)#### fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a, Global> Notable traits for [Box](../boxed/struct.box "struct std::boxed::Box")<I, A> ``` impl<I, A> Iterator for Box<I, A>where     I: Iterator + ?Sized,     A: Allocator, type Item = <I as Iterator>::Item; impl<F, A> Future for Box<F, A>where     F: Future + Unpin + ?Sized,     A: Allocator + 'static, type Output = <F as Future>::Output; impl<R: Read + ?Sized> Read for Box<R> impl<W: Write + ?Sized> Write for Box<W> ``` Converts a [`str`](../primitive.str) into a box of dyn [`Error`](trait.error "Error") + [`Send`](../marker/trait.send "Send") + [`Sync`](../marker/trait.sync "Sync"). ##### Examples ``` use std::error::Error; use std::mem; let a_str_error = "a str error"; let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error); assert!( mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error)) ``` [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2358)1.22.0 · ### impl<'a> From<Cow<'a, str>> for Box<dyn Error + 'static, Global> [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2372)#### fn from(err: Cow<'a, str>) -> Box<dyn Error + 'static, Global> Notable traits for [Box](../boxed/struct.box "struct std::boxed::Box")<I, A> ``` impl<I, A> Iterator for Box<I, A>where     I: Iterator + ?Sized,     A: Allocator, type Item = <I as Iterator>::Item; impl<F, A> Future for Box<F, A>where     F: Future + Unpin + ?Sized,     A: Allocator + 'static, type Output = <F as Future>::Output; impl<R: Read + ?Sized> Read for Box<R> impl<W: Write + ?Sized> Write for Box<W> ``` Converts a [`Cow`](../borrow/enum.cow "Cow") into a box of dyn [`Error`](trait.error "Error"). ##### Examples ``` use std::error::Error; use std::mem; use std::borrow::Cow; let a_cow_str_error = Cow::from("a str error"); let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error); assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error)) ``` [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2335)1.22.0 · ### impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a, Global> [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2350)#### fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a, Global> Notable traits for [Box](../boxed/struct.box "struct std::boxed::Box")<I, A> ``` impl<I, A> Iterator for Box<I, A>where     I: Iterator + ?Sized,     A: Allocator, type Item = <I as Iterator>::Item; impl<F, A> Future for Box<F, A>where     F: Future + Unpin + ?Sized,     A: Allocator + 'static, type Output = <F as Future>::Output; impl<R: Read + ?Sized> Read for Box<R> impl<W: Write + ?Sized> Write for Box<W> ``` Converts a [`Cow`](../borrow/enum.cow "Cow") into a box of dyn [`Error`](trait.error "Error") + [`Send`](../marker/trait.send "Send") + [`Sync`](../marker/trait.sync "Sync"). ##### Examples ``` use std::error::Error; use std::mem; use std::borrow::Cow; let a_cow_str_error = Cow::from("a str error"); let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error); assert!( mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error)) ``` [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2145)### impl<'a, E> From<E> for Box<dyn Error + 'a, Global>where E: 'a + [Error](trait.error "trait std::error::Error"), [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2171)#### fn from(err: E) -> Box<dyn Error + 'a, Global> Notable traits for [Box](../boxed/struct.box "struct std::boxed::Box")<I, A> ``` impl<I, A> Iterator for Box<I, A>where     I: Iterator + ?Sized,     A: Allocator, type Item = <I as Iterator>::Item; impl<F, A> Future for Box<F, A>where     F: Future + Unpin + ?Sized,     A: Allocator + 'static, type Output = <F as Future>::Output; impl<R: Read + ?Sized> Read for Box<R> impl<W: Write + ?Sized> Write for Box<W> ``` Converts a type of [`Error`](trait.error "Error") into a box of dyn [`Error`](trait.error "Error"). ##### Examples ``` use std::error::Error; use std::fmt; use std::mem; #[derive(Debug)] struct AnError; impl fmt::Display for AnError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "An error") } } impl Error for AnError {} let an_error = AnError; assert!(0 == mem::size_of_val(&an_error)); let a_boxed_error = Box::<dyn Error>::from(an_error); assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error)) ``` [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2179)### impl<'a, E> From<E> for Box<dyn Error + Send + Sync + 'a, Global>where E: 'a + [Error](trait.error "trait std::error::Error") + [Send](../marker/trait.send "trait std::marker::Send") + [Sync](../marker/trait.sync "trait std::marker::Sync"), [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2211)#### fn from(err: E) -> Box<dyn Error + Send + Sync + 'a, Global> Notable traits for [Box](../boxed/struct.box "struct std::boxed::Box")<I, A> ``` impl<I, A> Iterator for Box<I, A>where     I: Iterator + ?Sized,     A: Allocator, type Item = <I as Iterator>::Item; impl<F, A> Future for Box<F, A>where     F: Future + Unpin + ?Sized,     A: Allocator + 'static, type Output = <F as Future>::Output; impl<R: Read + ?Sized> Read for Box<R> impl<W: Write + ?Sized> Write for Box<W> ``` Converts a type of [`Error`](trait.error "Error") + [`Send`](../marker/trait.send "Send") + [`Sync`](../marker/trait.sync "Sync") into a box of dyn [`Error`](trait.error "Error") + [`Send`](../marker/trait.send "Send") + [`Sync`](../marker/trait.sync "Sync"). ##### Examples ``` use std::error::Error; use std::fmt; use std::mem; #[derive(Debug)] struct AnError; impl fmt::Display for AnError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "An error") } } impl Error for AnError {} unsafe impl Send for AnError {} unsafe impl Sync for AnError {} let an_error = AnError; assert!(0 == mem::size_of_val(&an_error)); let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error); assert!( mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error)) ``` [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2264)1.6.0 · ### impl From<String> for Box<dyn Error + 'static, Global> [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2277)#### fn from(str\_err: String) -> Box<dyn Error + 'static, Global> Notable traits for [Box](../boxed/struct.box "struct std::boxed::Box")<I, A> ``` impl<I, A> Iterator for Box<I, A>where     I: Iterator + ?Sized,     A: Allocator, type Item = <I as Iterator>::Item; impl<F, A> Future for Box<F, A>where     F: Future + Unpin + ?Sized,     A: Allocator + 'static, type Output = <F as Future>::Output; impl<R: Read + ?Sized> Read for Box<R> impl<W: Write + ?Sized> Write for Box<W> ``` Converts a [`String`](../string/struct.string "String") into a box of dyn [`Error`](trait.error "Error"). ##### Examples ``` use std::error::Error; use std::mem; let a_string_error = "a string error".to_string(); let a_boxed_error = Box::<dyn Error>::from(a_string_error); assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error)) ``` [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2219)### impl From<String> for Box<dyn Error + Send + Sync + 'static, Global> [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2234)#### fn from(err: String) -> Box<dyn Error + Send + Sync + 'static, Global> Notable traits for [Box](../boxed/struct.box "struct std::boxed::Box")<I, A> ``` impl<I, A> Iterator for Box<I, A>where     I: Iterator + ?Sized,     A: Allocator, type Item = <I as Iterator>::Item; impl<F, A> Future for Box<F, A>where     F: Future + Unpin + ?Sized,     A: Allocator + 'static, type Output = <F as Future>::Output; impl<R: Read + ?Sized> Read for Box<R> impl<W: Write + ?Sized> Write for Box<W> ``` Converts a [`String`](../string/struct.string "String") into a box of dyn [`Error`](trait.error "Error") + [`Send`](../marker/trait.send "Send") + [`Sync`](../marker/trait.sync "Sync"). ##### Examples ``` use std::error::Error; use std::mem; let a_string_error = "a string error".to_string(); let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error); assert!( mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error)) ``` Implementors ------------ [source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2646)### impl !Error for &str [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)1.8.0 · ### impl Error for Infallible [source](https://doc.rust-lang.org/src/std/env.rs.html#308-316)### impl Error for VarError [source](https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#1647-1655)1.15.0 · ### impl Error for RecvTimeoutError [source](https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#1612-1620)### impl Error for TryRecvError [source](https://doc.rust-lang.org/src/core/error.rs.html#215)### impl Error for ! [source](https://doc.rust-lang.org/src/core/error.rs.html#508)### impl Error for FromBytesUntilNulError [source](https://doc.rust-lang.org/src/core/alloc/mod.rs.html#43)### impl Error for AllocError [source](https://doc.rust-lang.org/src/core/alloc/layout.rs.html#468)1.28.0 · ### impl Error for LayoutError [source](https://doc.rust-lang.org/src/core/array/mod.rs.html#126)1.34.0 · ### impl Error for TryFromSliceError [source](https://doc.rust-lang.org/src/core/error.rs.html#465)1.13.0 · ### impl Error for BorrowError [source](https://doc.rust-lang.org/src/core/error.rs.html#473)1.13.0 · ### impl Error for BorrowMutError [source](https://doc.rust-lang.org/src/core/error.rs.html#481)1.34.0 · ### impl Error for CharTryFromError [source](https://doc.rust-lang.org/src/core/char/decode.rs.html#129)1.9.0 · ### impl Error for DecodeUtf16Error [source](https://doc.rust-lang.org/src/core/error.rs.html#489)1.20.0 · ### impl Error for ParseCharError [source](https://doc.rust-lang.org/src/core/char/mod.rs.html#592)1.59.0 · ### impl Error for TryFromCharError [source](https://doc.rust-lang.org/src/alloc/collections/mod.rs.html#158)1.57.0 · ### impl Error for TryReserveError [source](https://doc.rust-lang.org/src/std/env.rs.html#545-550)### impl Error for JoinPathsError [source](https://doc.rust-lang.org/src/core/error.rs.html#500)1.17.0 · ### impl Error for FromBytesWithNulError [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#1136)1.58.0 · ### impl Error for FromVecWithNulError [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#1140)1.7.0 · ### impl Error for IntoStringError [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#1127)### impl Error for NulError [source](https://doc.rust-lang.org/src/core/error.rs.html#457)1.11.0 · ### impl Error for std::fmt::Error [source](https://doc.rust-lang.org/src/std/io/error.rs.html#938-966)### impl Error for std::io::Error [source](https://doc.rust-lang.org/src/std/io/buffered/bufwriter.rs.html#490-495)1.56.0 · ### impl Error for WriterPanicked [source](https://doc.rust-lang.org/src/std/net/parser.rs.html#488-500)1.4.0 · ### impl Error for AddrParseError [source](https://doc.rust-lang.org/src/core/num/mod.rs.html#65)### impl Error for ParseFloatError [source](https://doc.rust-lang.org/src/core/num/error.rs.html#152)### impl Error for ParseIntError [source](https://doc.rust-lang.org/src/core/num/error.rs.html#161)1.34.0 · ### impl Error for TryFromIntError [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#282)1.63.0 · ### impl Error for InvalidHandleError Available on **Windows** only.[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#263)1.63.0 · ### impl Error for NullHandleError Available on **Windows** only.[source](https://doc.rust-lang.org/src/std/path.rs.html#3178-3183)1.7.0 · ### impl Error for StripPrefixError [source](https://doc.rust-lang.org/src/std/process.rs.html#1675)### impl Error for ExitStatusError [source](https://doc.rust-lang.org/src/core/str/error.rs.html#153)### impl Error for ParseBoolError [source](https://doc.rust-lang.org/src/core/str/error.rs.html#129)### impl Error for Utf8Error [source](https://doc.rust-lang.org/src/alloc/string.rs.html#1946)### impl Error for FromUtf8Error [source](https://doc.rust-lang.org/src/alloc/string.rs.html#1955)### impl Error for FromUtf16Error [source](https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#1594-1599)### impl Error for RecvError [source](https://doc.rust-lang.org/src/std/thread/local.rs.html#390)1.26.0 · ### impl Error for AccessError [source](https://doc.rust-lang.org/src/core/error.rs.html#497)### impl Error for FromFloatSecsError [source](https://doc.rust-lang.org/src/std/time.rs.html#670-675)1.8.0 · ### impl Error for SystemTimeError [source](https://doc.rust-lang.org/src/alloc/collections/btree/map/entry.rs.html#138-139)### impl<'a, K, V> Error for std::collections::btree\_map::OccupiedError<'a, K, V, Global>where K: [Debug](../fmt/trait.debug "trait std::fmt::Debug") + [Ord](../cmp/trait.ord "trait std::cmp::Ord"), V: [Debug](../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2165-2170)### impl<'a, K: Debug, V: Debug> Error for std::collections::hash\_map::OccupiedError<'a, K, V> [source](https://doc.rust-lang.org/src/core/error.rs.html#436)1.51.0 · ### impl<'a, T> Error for &'a Twhere T: [Error](trait.error "trait std::error::Error") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/std/sync/poison.rs.html#246-262)### impl<T> Error for TryLockError<T> [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2379)1.8.0 · ### impl<T> Error for Box<T, Global>where T: [Error](trait.error "trait std::error::Error"), [source](https://doc.rust-lang.org/src/alloc/boxed/thin.rs.html#279)### impl<T> Error for ThinBox<T>where T: [Error](trait.error "trait std::error::Error") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2769)1.52.0 · ### impl<T> Error for Arc<T>where T: [Error](trait.error "trait std::error::Error") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/std/sync/poison.rs.html#156-161)### impl<T> Error for PoisonError<T> [source](https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#1562-1570)### impl<T: Send> Error for TrySendError<T> [source](https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#1534-1539)### impl<T: Send> Error for SendError<T> [source](https://doc.rust-lang.org/src/std/io/buffered/mod.rs.html#184-189)### impl<W: Send + Debug> Error for IntoInnerError<W>
programming_docs
rust Struct std::error::Report Struct std::error::Report ========================= ``` pub struct Report<E = Box<dyn Error>> { /* private fields */ } ``` 🔬This is a nightly-only experimental API. (`error_reporter` [#90172](https://github.com/rust-lang/rust/issues/90172)) An error reporter that prints an error and its sources. Report also exposes configuration options for formatting the error sources, either entirely on a single line, or in multi-line format with each source on a new line. `Report` only requires that the wrapped error implement `Error`. It doesn’t require that the wrapped error be `Send`, `Sync`, or `'static`. Examples -------- ``` #![feature(error_reporter)] use std::error::{Error, Report}; use std::fmt; #[derive(Debug)] struct SuperError { source: SuperErrorSideKick, } impl fmt::Display for SuperError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SuperError is here!") } } impl Error for SuperError { fn source(&self) -> Option<&(dyn Error + 'static)> { Some(&self.source) } } #[derive(Debug)] struct SuperErrorSideKick; impl fmt::Display for SuperErrorSideKick { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SuperErrorSideKick is here!") } } impl Error for SuperErrorSideKick {} fn get_super_error() -> Result<(), SuperError> { Err(SuperError { source: SuperErrorSideKick }) } fn main() { match get_super_error() { Err(e) => println!("Error: {}", Report::new(e)), _ => println!("No error"), } } ``` This example produces the following output: ``` Error: SuperError is here!: SuperErrorSideKick is here! ``` ### Output consistency Report prints the same output via `Display` and `Debug`, so it works well with [`Result::unwrap`](../result/enum.result#method.unwrap "Result::unwrap")/[`Result::expect`](../result/enum.result#method.expect "Result::expect") which print their `Err` variant via `Debug`: ⓘ ``` #![feature(error_reporter)] use std::error::Report; get_super_error().map_err(Report::new).unwrap(); ``` This example produces the following output: ``` thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: SuperError is here!: SuperErrorSideKick is here!', src/error.rs:34:40 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` ### Return from `main` `Report` also implements `From` for all types that implement [`Error`](trait.error "Error"); this when combined with the `Debug` output means `Report` is an ideal starting place for formatting errors returned from `main`. ⓘ ``` #![feature(error_reporter)] use std::error::Report; fn main() -> Result<(), Report<SuperError>> { get_super_error()?; Ok(()) } ``` This example produces the following output: ``` Error: SuperError is here!: SuperErrorSideKick is here! ``` **Note**: `Report`s constructed via `?` and `From` will be configured to use the single line output format. If you want to make sure your `Report`s are pretty printed and include backtrace you will need to manually convert and enable those flags. ⓘ ``` #![feature(error_reporter)] use std::error::Report; fn main() -> Result<(), Report<SuperError>> { get_super_error() .map_err(Report::from) .map_err(|r| r.pretty(true).show_backtrace(true))?; Ok(()) } ``` This example produces the following output: ``` Error: SuperError is here! Caused by: SuperErrorSideKick is here! ``` Implementations --------------- [source](https://doc.rust-lang.org/src/std/error.rs.html#1261-1270)### impl<E> Report<E>where [Report](struct.report "struct std::error::Report")<E>: [From](../convert/trait.from "trait std::convert::From")<E>, [source](https://doc.rust-lang.org/src/std/error.rs.html#1267-1269)#### pub fn new(error: E) -> Report<E> 🔬This is a nightly-only experimental API. (`error_reporter` [#90172](https://github.com/rust-lang/rust/issues/90172)) Create a new `Report` from an input error. [source](https://doc.rust-lang.org/src/std/error.rs.html#1272-1475)### impl<E> Report<E> [source](https://doc.rust-lang.org/src/std/error.rs.html#1381-1384)#### pub fn pretty(self, pretty: bool) -> Self 🔬This is a nightly-only experimental API. (`error_reporter` [#90172](https://github.com/rust-lang/rust/issues/90172)) Enable pretty-printing the report across multiple lines. ##### Examples ``` #![feature(error_reporter)] use std::error::Report; let error = SuperError { source: SuperErrorSideKick }; let report = Report::new(error).pretty(true); eprintln!("Error: {report:?}"); ``` This example produces the following output: ``` Error: SuperError is here! Caused by: SuperErrorSideKick is here! ``` When there are multiple source errors the causes will be numbered in order of iteration starting from the outermost error. ``` #![feature(error_reporter)] use std::error::Report; let source = SuperErrorSideKickSideKick; let source = SuperErrorSideKick { source }; let error = SuperError { source }; let report = Report::new(error).pretty(true); eprintln!("Error: {report:?}"); ``` This example produces the following output: ``` Error: SuperError is here! Caused by: 0: SuperErrorSideKick is here! 1: SuperErrorSideKickSideKick is here! ``` [source](https://doc.rust-lang.org/src/std/error.rs.html#1471-1474)#### pub fn show\_backtrace(self, show\_backtrace: bool) -> Self 🔬This is a nightly-only experimental API. (`error_reporter` [#90172](https://github.com/rust-lang/rust/issues/90172)) Display backtrace if available when using pretty output format. ##### Examples **Note**: Report will search for the first `Backtrace` it can find starting from the outermost error. In this example it will display the backtrace from the second error in the sources, `SuperErrorSideKick`. ``` #![feature(error_reporter)] #![feature(provide_any)] #![feature(error_generic_member_access)] use std::any::Demand; use std::error::Report; use std::backtrace::Backtrace; #[derive(Debug)] struct SuperErrorSideKick { backtrace: Backtrace, } impl SuperErrorSideKick { fn new() -> SuperErrorSideKick { SuperErrorSideKick { backtrace: Backtrace::force_capture() } } } impl Error for SuperErrorSideKick { fn provide<'a>(&'a self, demand: &mut Demand<'a>) { demand.provide_ref::<Backtrace>(&self.backtrace); } } // The rest of the example is unchanged ... let source = SuperErrorSideKick::new(); let error = SuperError { source }; let report = Report::new(error).pretty(true).show_backtrace(true); eprintln!("Error: {report:?}"); ``` This example produces something similar to the following output: ``` Error: SuperError is here! Caused by: SuperErrorSideKick is here! Stack backtrace: 0: rust_out::main::_doctest_main_src_error_rs_1158_0::SuperErrorSideKick::new 1: rust_out::main::_doctest_main_src_error_rs_1158_0 2: rust_out::main 3: core::ops::function::FnOnce::call_once 4: std::sys_common::backtrace::__rust_begin_short_backtrace 5: std::rt::lang_start::{{closure}} 6: std::panicking::try 7: std::rt::lang_start_internal 8: std::rt::lang_start 9: main 10: __libc_start_main 11: _start ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/error.rs.html#1569-1576)### impl<E> Debug for Report<E>where [Report](struct.report "struct std::error::Report")<E>: [Display](../fmt/trait.display "trait std::fmt::Display"), [source](https://doc.rust-lang.org/src/std/error.rs.html#1573-1575)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/error.rs.html#1557-1564)### impl<E> Display for Report<E>where E: [Error](trait.error "trait std::error::Error"), [source](https://doc.rust-lang.org/src/std/error.rs.html#1561-1563)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/error.rs.html#1547-1554)### impl<E> From<E> for Report<E>where E: [Error](trait.error "trait std::error::Error"), [source](https://doc.rust-lang.org/src/std/error.rs.html#1551-1553)#### fn from(error: E) -> Self Converts to this type from the input type. Auto Trait Implementations -------------------------- ### impl<E> RefUnwindSafe for Report<E>where E: [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<E> Send for Report<E>where E: [Send](../marker/trait.send "trait std::marker::Send"), ### impl<E> Sync for Report<E>where E: [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<E> Unpin for Report<E>where E: [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), ### impl<E> UnwindSafe for Report<E>where E: [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#577)### impl<T> From<!> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#578)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: !) -> T Converts to this type from the input type. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2500)### impl<T> ToString for Twhere T: [Display](../fmt/trait.display "trait std::fmt::Display") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2506)#### default fn to\_string(&self) -> String Converts the given value to a `String`. [Read more](../string/trait.tostring#tymethod.to_string) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Module std::future Module std::future ================== Asynchronous basic functionality. Please see the fundamental [`async`](../keyword.async) and [`await`](../keyword.await) keywords and the [async book](https://rust-lang.github.io/async-book/) for more information on asynchronous programming in Rust. Macros ------ [join](macro.join "std::future::join macro")Experimental Polls multiple futures simultaneously, returning a tuple of all results once complete. Structs ------- [Pending](struct.pending "std::future::Pending struct") Creates a future which never resolves, representing a computation that never finishes. [PollFn](struct.pollfn "std::future::PollFn struct") A Future that wraps a function returning [`Poll`](../task/enum.poll "Poll"). [Ready](struct.ready "std::future::Ready struct") A future that is immediately ready with a value. Traits ------ [Future](trait.future "std::future::Future trait") A future represents an asynchronous computation obtained by use of [`async`](../keyword.async). [IntoFuture](trait.intofuture "std::future::IntoFuture trait") Conversion into a `Future`. Functions --------- [pending](fn.pending "std::future::pending fn") Creates a future which never resolves, representing a computation that never finishes. [poll\_fn](fn.poll_fn "std::future::poll_fn fn") Creates a future that wraps a function returning [`Poll`](../task/enum.poll "Poll"). [ready](fn.ready "std::future::ready fn") Creates a future that is immediately ready with a value. rust Function std::future::poll_fn Function std::future::poll\_fn ============================== ``` pub fn poll_fn<T, F>(f: F) -> PollFn<F>ⓘNotable traits for PollFn<F>impl<T, F> Future for PollFn<F>where    F: FnMut(&mut Context<'_>) -> Poll<T>, type Output = T;where    F: FnMut(&mut Context<'_>) -> Poll<T>, ``` Creates a future that wraps a function returning [`Poll`](../task/enum.poll "Poll"). Polling the future delegates to the wrapped function. If the returned future is pinned, then the captured environment of the wrapped function is also pinned in-place, so as long as the closure does not move out of its captures it can soundly create pinned references to them. Examples -------- ``` use core::future::poll_fn; use std::task::{Context, Poll}; fn read_line(_cx: &mut Context<'_>) -> Poll<String> { Poll::Ready("Hello, World!".into()) } let read_future = poll_fn(read_line); assert_eq!(read_future.await, "Hello, World!".to_owned()); ``` rust Struct std::future::Ready Struct std::future::Ready ========================= ``` pub struct Ready<T>(_); ``` A future that is immediately ready with a value. This `struct` is created by [`ready()`](fn.ready "ready()"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/future/ready.rs.html#10)### impl<T> Clone for Ready<T>where T: [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/core/future/ready.rs.html#10)#### fn clone(&self) -> Ready<T> Notable traits for [Ready](struct.ready "struct std::future::Ready")<T> ``` impl<T> Future for Ready<T> type Output = T; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/future/ready.rs.html#10)### impl<T> Debug for Ready<T>where T: [Debug](../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/core/future/ready.rs.html#10)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/future/ready.rs.html#18)### impl<T> Future for Ready<T> #### type Output = T The type of value produced on completion. [source](https://doc.rust-lang.org/src/core/future/ready.rs.html#22)#### fn poll(self: Pin<&mut Ready<T>>, \_cx: &mut Context<'\_>) -> Poll<T> Attempt to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. [Read more](trait.future#tymethod.poll) [source](https://doc.rust-lang.org/src/core/future/ready.rs.html#15)### impl<T> Unpin for Ready<T> Auto Trait Implementations -------------------------- ### impl<T> RefUnwindSafe for Ready<T>where T: [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<T> Send for Ready<T>where T: [Send](../marker/trait.send "trait std::marker::Send"), ### impl<T> Sync for Ready<T>where T: [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<T> UnwindSafe for Ready<T>where T: [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/future/into_future.rs.html#132)### impl<F> IntoFuture for Fwhere F: [Future](trait.future "trait std::future::Future"), #### type Output = <F as Future>::Output The output that the future will produce on completion. #### type IntoFuture = F Which kind of future are we turning this into? [source](https://doc.rust-lang.org/src/core/future/into_future.rs.html#136)#### fn into\_future(self) -> <F as IntoFuture>::IntoFuture Creates a future from a value. [Read more](trait.intofuture#tymethod.into_future) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Function std::future::ready Function std::future::ready =========================== ``` pub fn ready<T>(t: T) -> Ready<T>ⓘNotable traits for Ready<T>impl<T> Future for Ready<T> type Output = T; ``` Creates a future that is immediately ready with a value. Futures created through this function are functionally similar to those created through `async {}`. The main difference is that futures created through this function are named and implement `Unpin`. Examples -------- ``` use std::future; let a = future::ready(1); assert_eq!(a.await, 1); ``` rust Macro std::future::join Macro std::future::join ======================= ``` pub macro join($($fut:expr),+ $(,)?) { ... } ``` 🔬This is a nightly-only experimental API. (`future_join` [#91642](https://github.com/rust-lang/rust/issues/91642)) Polls multiple futures simultaneously, returning a tuple of all results once complete. While `join!(a, b).await` is similar to `(a.await, b.await)`, `join!` polls both futures concurrently and is therefore more efficient. Examples -------- ``` #![feature(future_join)] use std::future::join; async fn one() -> usize { 1 } async fn two() -> usize { 2 } let x = join!(one(), two()).await; assert_eq!(x, (1, 2)); ``` `join!` is variadic, so you can pass any number of futures: ``` #![feature(future_join)] use std::future::join; async fn one() -> usize { 1 } async fn two() -> usize { 2 } async fn three() -> usize { 3 } let x = join!(one(), two(), three()).await; assert_eq!(x, (1, 2, 3)); ``` rust Trait std::future::Future Trait std::future::Future ========================= ``` pub trait Future { type Output; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>; } ``` A future represents an asynchronous computation obtained by use of [`async`](../keyword.async). A future is a value that might not have finished computing yet. This kind of “asynchronous value” makes it possible for a thread to continue doing useful work while it waits for the value to become available. The `poll` method ----------------- The core method of future, `poll`, *attempts* to resolve the future into a final value. This method does not block if the value is not ready. Instead, the current task is scheduled to be woken up when it’s possible to make further progress by `poll`ing again. The `context` passed to the `poll` method can provide a [`Waker`](../task/struct.waker), which is a handle for waking up the current task. When using a future, you generally won’t call `poll` directly, but instead `.await` the value. Required Associated Types ------------------------- [source](https://doc.rust-lang.org/src/core/future/future.rs.html#40)#### type Output The type of value produced on completion. Required Methods ---------------- [source](https://doc.rust-lang.org/src/core/future/future.rs.html#104)#### fn poll(self: Pin<&mut Self>, cx: &mut Context<'\_>) -> Poll<Self::Output> Attempt to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. ##### Return value This function returns: * [`Poll::Pending`](../task/enum.poll#variant.Pending "Poll::Pending") if the future is not ready yet * [`Poll::Ready(val)`](../task/enum.poll#variant.Ready) with the result `val` of this future if it finished successfully. Once a future has finished, clients should not `poll` it again. When a future is not ready yet, `poll` returns `Poll::Pending` and stores a clone of the [`Waker`](../task/struct.waker) copied from the current [`Context`](../task/struct.context "Context"). This [`Waker`](../task/struct.waker) is then woken once the future can make progress. For example, a future waiting for a socket to become readable would call `.clone()` on the [`Waker`](../task/struct.waker) and store it. When a signal arrives elsewhere indicating that the socket is readable, [`Waker::wake`](../task/struct.waker#method.wake) is called and the socket future’s task is awoken. Once a task has been woken up, it should attempt to `poll` the future again, which may or may not produce a final value. Note that on multiple calls to `poll`, only the [`Waker`](../task/struct.waker) from the [`Context`](../task/struct.context "Context") passed to the most recent call should be scheduled to receive a wakeup. ##### Runtime characteristics Futures alone are *inert*; they must be *actively* `poll`ed to make progress, meaning that each time the current task is woken up, it should actively re-`poll` pending futures that it still has an interest in. The `poll` function is not called repeatedly in a tight loop – instead, it should only be called when the future indicates that it is ready to make progress (by calling `wake()`). If you’re familiar with the `poll(2)` or `select(2)` syscalls on Unix it’s worth noting that futures typically do *not* suffer the same problems of “all wakeups must poll all events”; they are more like `epoll(4)`. An implementation of `poll` should strive to return quickly, and should not block. Returning quickly prevents unnecessarily clogging up threads or event loops. If it is known ahead of time that a call to `poll` may end up taking awhile, the work should be offloaded to a thread pool (or something similar) to ensure that `poll` can return quickly. ##### Panics Once a future has completed (returned `Ready` from `poll`), calling its `poll` method again may panic, block forever, or cause other kinds of problems; the `Future` trait places no requirements on the effects of such a call. However, as the `poll` method is not marked `unsafe`, Rust’s usual rules apply: calls must never cause undefined behavior (memory corruption, incorrect use of `unsafe` functions, or the like), regardless of the future’s state. Implementors ------------ [source](https://doc.rust-lang.org/src/core/future/future.rs.html#108)### impl<F> Future for &mut Fwhere F: [Future](trait.future "trait std::future::Future") + [Unpin](../marker/trait.unpin "trait std::marker::Unpin") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), #### type Output = <F as Future>::Output [source](https://doc.rust-lang.org/src/core/panic/unwind_safe.rs.html#290)### impl<F> Future for AssertUnwindSafe<F>where F: [Future](trait.future "trait std::future::Future"), #### type Output = <F as Future>::Output [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2070)### impl<F, A> Future for Box<F, A>where F: [Future](trait.future "trait std::future::Future") + [Unpin](../marker/trait.unpin "trait std::marker::Unpin") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator") + 'static, #### type Output = <F as Future>::Output [source](https://doc.rust-lang.org/src/core/future/future.rs.html#117)### impl<P> Future for Pin<P>where P: [DerefMut](../ops/trait.derefmut "trait std::ops::DerefMut"), <P as [Deref](../ops/trait.deref "trait std::ops::Deref")>::[Target](../ops/trait.deref#associatedtype.Target "type std::ops::Deref::Target"): [Future](trait.future "trait std::future::Future"), #### type Output = <<P as Deref>::Target as Future>::Output [source](https://doc.rust-lang.org/src/core/sync/exclusive.rs.html#167)### impl<T> Future for Exclusive<T>where T: [Future](trait.future "trait std::future::Future") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), #### type Output = <T as Future>::Output [source](https://doc.rust-lang.org/src/core/future/pending.rs.html#38)1.48.0 · ### impl<T> Future for Pending<T> #### type Output = T [source](https://doc.rust-lang.org/src/core/future/ready.rs.html#18)1.48.0 · ### impl<T> Future for Ready<T> #### type Output = T [source](https://doc.rust-lang.org/src/core/future/poll_fn.rs.html#56)1.64.0 · ### impl<T, F> Future for PollFn<F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&mut [Context](../task/struct.context "struct std::task::Context")<'\_>) -> [Poll](../task/enum.poll "enum std::task::Poll")<T>, #### type Output = T rust Struct std::future::PollFn Struct std::future::PollFn ========================== ``` pub struct PollFn<F> { /* private fields */ } ``` A Future that wraps a function returning [`Poll`](../task/enum.poll "Poll"). This `struct` is created by [`poll_fn()`](fn.poll_fn "poll_fn()"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/future/poll_fn.rs.html#49)### impl<F> Debug for PollFn<F> [source](https://doc.rust-lang.org/src/core/future/poll_fn.rs.html#50)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/future/poll_fn.rs.html#56)### impl<T, F> Future for PollFn<F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&mut [Context](../task/struct.context "struct std::task::Context")<'\_>) -> [Poll](../task/enum.poll "enum std::task::Poll")<T>, #### type Output = T The type of value produced on completion. [source](https://doc.rust-lang.org/src/core/future/poll_fn.rs.html#62)#### fn poll(self: Pin<&mut PollFn<F>>, cx: &mut Context<'\_>) -> Poll<T> Attempt to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. [Read more](trait.future#tymethod.poll) [source](https://doc.rust-lang.org/src/core/future/poll_fn.rs.html#46)### impl<F> Unpin for PollFn<F>where F: [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), Auto Trait Implementations -------------------------- ### impl<F> RefUnwindSafe for PollFn<F>where F: [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<F> Send for PollFn<F>where F: [Send](../marker/trait.send "trait std::marker::Send"), ### impl<F> Sync for PollFn<F>where F: [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<F> UnwindSafe for PollFn<F>where F: [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/future/into_future.rs.html#132)### impl<F> IntoFuture for Fwhere F: [Future](trait.future "trait std::future::Future"), #### type Output = <F as Future>::Output The output that the future will produce on completion. #### type IntoFuture = F Which kind of future are we turning this into? [source](https://doc.rust-lang.org/src/core/future/into_future.rs.html#136)#### fn into\_future(self) -> <F as IntoFuture>::IntoFuture Creates a future from a value. [Read more](trait.intofuture#tymethod.into_future) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Struct std::future::Pending Struct std::future::Pending =========================== ``` pub struct Pending<T> { /* private fields */ } ``` Creates a future which never resolves, representing a computation that never finishes. This `struct` is created by [`pending()`](fn.pending "pending()"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/future/pending.rs.html#54)### impl<T> Clone for Pending<T> [source](https://doc.rust-lang.org/src/core/future/pending.rs.html#55)#### fn clone(&self) -> Pending<T> Notable traits for [Pending](struct.pending "struct std::future::Pending")<T> ``` impl<T> Future for Pending<T> type Output = T; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/future/pending.rs.html#47)### impl<T> Debug for Pending<T> [source](https://doc.rust-lang.org/src/core/future/pending.rs.html#48)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/future/pending.rs.html#38)### impl<T> Future for Pending<T> #### type Output = T The type of value produced on completion. [source](https://doc.rust-lang.org/src/core/future/pending.rs.html#41)#### fn poll(self: Pin<&mut Pending<T>>, &mut Context<'\_>) -> Poll<T> Attempt to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. [Read more](trait.future#tymethod.poll) Auto Trait Implementations -------------------------- ### impl<T> RefUnwindSafe for Pending<T> ### impl<T> Send for Pending<T> ### impl<T> Sync for Pending<T> ### impl<T> Unpin for Pending<T> ### impl<T> UnwindSafe for Pending<T> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/future/into_future.rs.html#132)### impl<F> IntoFuture for Fwhere F: [Future](trait.future "trait std::future::Future"), #### type Output = <F as Future>::Output The output that the future will produce on completion. #### type IntoFuture = F Which kind of future are we turning this into? [source](https://doc.rust-lang.org/src/core/future/into_future.rs.html#136)#### fn into\_future(self) -> <F as IntoFuture>::IntoFuture Creates a future from a value. [Read more](trait.intofuture#tymethod.into_future) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Function std::future::pending Function std::future::pending ============================= ``` pub fn pending<T>() -> Pending<T>ⓘNotable traits for Pending<T>impl<T> Future for Pending<T> type Output = T; ``` Creates a future which never resolves, representing a computation that never finishes. Examples -------- ``` use std::future; let future = future::pending(); let () = future.await; unreachable!(); ``` rust Trait std::future::IntoFuture Trait std::future::IntoFuture ============================= ``` pub trait IntoFuture { type Output; type IntoFuture: Future    where        <Self::IntoFuture as Future>::Output == Self::Output; fn into_future(self) -> Self::IntoFuture; } ``` Conversion into a `Future`. By implementing `IntoFuture` for a type, you define how it will be converted to a future. `.await` desugaring -------------------- The `.await` keyword desugars into a call to `IntoFuture::into_future` first before polling the future to completion. `IntoFuture` is implemented for all `T: Future` which means the `into_future` method will be available on all futures. ``` use std::future::IntoFuture; let v = async { "meow" }; let mut fut = v.into_future(); assert_eq!("meow", fut.await); ``` Async builders -------------- When implementing futures manually there will often be a choice between implementing `Future` or `IntoFuture` for a type. Implementing `Future` is a good choice in most cases. But implementing `IntoFuture` is most useful when implementing “async builder” types, which allow their values to be modified multiple times before being `.await`ed. ``` use std::future::{ready, Ready, IntoFuture}; /// Eventually multiply two numbers pub struct Multiply { num: u16, factor: u16, } impl Multiply { /// Construct a new instance of `Multiply`. pub fn new(num: u16, factor: u16) -> Self { Self { num, factor } } /// Set the number to multiply by the factor. pub fn number(mut self, num: u16) -> Self { self.num = num; self } /// Set the factor to multiply the number with. pub fn factor(mut self, factor: u16) -> Self { self.factor = factor; self } } impl IntoFuture for Multiply { type Output = u16; type IntoFuture = Ready<Self::Output>; fn into_future(self) -> Self::IntoFuture { ready(self.num * self.factor) } } // NOTE: Rust does not yet have an `async fn main` function, that functionality // currently only exists in the ecosystem. async fn run() { let num = Multiply::new(0, 0) // initialize the builder to number: 0, factor: 0 .number(2) // change the number to 2 .factor(2) // change the factor to 2 .await; // convert to future and .await assert_eq!(num, 4); } ``` Usage in trait bounds --------------------- Using `IntoFuture` in trait bounds allows a function to be generic over both `Future` and `IntoFuture`. This is convenient for users of the function, so when they are using it they don’t have to make an extra call to `IntoFuture::into_future` to obtain an instance of `Future`: ``` use std::future::IntoFuture; /// Convert the output of a future to a string. async fn fut_to_string<Fut>(fut: Fut) -> String where Fut: IntoFuture, Fut::Output: std::fmt::Debug, { format!("{:?}", fut.await) } ``` Required Associated Types ------------------------- [source](https://doc.rust-lang.org/src/core/future/into_future.rs.html#105)#### type Output The output that the future will produce on completion. [source](https://doc.rust-lang.org/src/core/future/into_future.rs.html#109)#### type IntoFuture: Futurewhere <Self::[IntoFuture](trait.intofuture#associatedtype.IntoFuture "type std::future::IntoFuture::IntoFuture") as [Future](trait.future "trait std::future::Future")>::[Output](trait.future#associatedtype.Output "type std::future::Future::Output") == Self::[Output](trait.intofuture#associatedtype.Output "type std::future::IntoFuture::Output") Which kind of future are we turning this into? Required Methods ---------------- [source](https://doc.rust-lang.org/src/core/future/into_future.rs.html#128)#### fn into\_future(self) -> Self::IntoFuture Creates a future from a value. ##### Examples Basic usage: ``` use std::future::IntoFuture; let v = async { "meow" }; let mut fut = v.into_future(); assert_eq!("meow", fut.await); ``` Implementors ------------ [source](https://doc.rust-lang.org/src/core/future/into_future.rs.html#132)### impl<F> IntoFuture for Fwhere F: [Future](trait.future "trait std::future::Future"), #### type Output = <F as Future>::Output #### type IntoFuture = F rust Module std::u16 Module std::u16 =============== 👎Deprecating in a future Rust version: all constants in this module replaced by associated constants on `u16` Constants for the 16-bit unsigned integer type. *[See also the `u16` primitive type](../primitive.u16 "u16").* New code should use the associated constants directly on the primitive type. Constants --------- [MAX](constant.max "std::u16::MAX constant")Deprecation planned The largest value that can be represented by this integer type. Use [`u16::MAX`](../primitive.u16#associatedconstant.MAX "u16::MAX") instead. [MIN](constant.min "std::u16::MIN constant")Deprecation planned The smallest value that can be represented by this integer type. Use [`u16::MIN`](../primitive.u16#associatedconstant.MIN "u16::MIN") instead. rust Constant std::u16::MAX Constant std::u16::MAX ====================== ``` pub const MAX: u16 = u16::MAX; // 65_535u16 ``` 👎Deprecating in a future Rust version: replaced by the `MAX` associated constant on this type The largest value that can be represented by this integer type. Use [`u16::MAX`](../primitive.u16#associatedconstant.MAX "u16::MAX") instead. Examples -------- ``` // deprecated way let max = std::u16::MAX; // intended way let max = u16::MAX; ``` rust Constant std::u16::MIN Constant std::u16::MIN ====================== ``` pub const MIN: u16 = u16::MIN; // 0u16 ``` 👎Deprecating in a future Rust version: replaced by the `MIN` associated constant on this type The smallest value that can be represented by this integer type. Use [`u16::MIN`](../primitive.u16#associatedconstant.MIN "u16::MIN") instead. Examples -------- ``` // deprecated way let min = std::u16::MIN; // intended way let min = u16::MIN; ``` rust Struct std::str::SplitAsciiWhitespace Struct std::str::SplitAsciiWhitespace ===================================== ``` pub struct SplitAsciiWhitespace<'a> { /* private fields */ } ``` An iterator over the non-ASCII-whitespace substrings of a string, separated by any amount of ASCII whitespace. This struct is created by the [`split_ascii_whitespace`](../primitive.str#method.split_ascii_whitespace) method on [`str`](../primitive.str "str"). See its documentation for more. Implementations --------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1292)### impl<'a> SplitAsciiWhitespace<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1312)#### pub fn as\_str(&self) -> &'a str 🔬This is a nightly-only experimental API. (`str_split_whitespace_as_str` [#77998](https://github.com/rust-lang/rust/issues/77998)) Returns remainder of the split string ##### Examples ``` #![feature(str_split_whitespace_as_str)] let mut split = "Mary had a little lamb".split_ascii_whitespace(); assert_eq!(split.as_str(), "Mary had a little lamb"); split.next(); assert_eq!(split.as_str(), "had a little lamb"); split.by_ref().for_each(drop); assert_eq!(split.as_str(), ""); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1187)### impl<'a> Clone for SplitAsciiWhitespace<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1187)#### fn clone(&self) -> SplitAsciiWhitespace<'a> Notable traits for [SplitAsciiWhitespace](struct.splitasciiwhitespace "struct std::str::SplitAsciiWhitespace")<'a> ``` impl<'a> Iterator for SplitAsciiWhitespace<'a> type Item = &'a str; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1187)### impl<'a> Debug for SplitAsciiWhitespace<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1187)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1282)### impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1284)#### fn next\_back(&mut self) -> Option<&'a str> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1262)### impl<'a> Iterator for SplitAsciiWhitespace<'a> #### type Item = &'a str The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1266)#### fn next(&mut self) -> Option<&'a str> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1271)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1276)#### fn last(self) -> Option<&'a str> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../primitive.reference) T>, P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&](../primitive.reference)T) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)1.0.0 · #### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)1.0.0 · #### fn cycle(self) -> Cycle<Self>where Self: [Clone](../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1290)### impl FusedIterator for SplitAsciiWhitespace<'\_> Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for SplitAsciiWhitespace<'a> ### impl<'a> Send for SplitAsciiWhitespace<'a> ### impl<'a> Sync for SplitAsciiWhitespace<'a> ### impl<'a> Unpin for SplitAsciiWhitespace<'a> ### impl<'a> UnwindSafe for SplitAsciiWhitespace<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::CharIndices Struct std::str::CharIndices ============================ ``` pub struct CharIndices<'a> { /* private fields */ } ``` An iterator over the [`char`](../primitive.char)s of a string slice, and their positions. This struct is created by the [`char_indices`](../primitive.str#method.char_indices) method on [`str`](../primitive.str "str"). See its documentation for more. Implementations --------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#182)### impl<'a> CharIndices<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#190)1.4.0 · #### pub fn as\_str(&self) -> &'a str Views the underlying data as a subslice of the original data. This has the same lifetime as the original slice, and so the iterator can continue to be used while this exists. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#215)#### pub fn offset(&self) -> usize 🔬This is a nightly-only experimental API. (`char_indices_offset` [#83871](https://github.com/rust-lang/rust/issues/83871)) Returns the byte position of the next character, or the length of the underlying string if there are no more characters. ##### Examples ``` #![feature(char_indices_offset)] let mut chars = "a楽".char_indices(); assert_eq!(chars.offset(), 0); assert_eq!(chars.next(), Some((0, 'a'))); assert_eq!(chars.offset(), 1); assert_eq!(chars.next(), Some((1, '楽'))); assert_eq!(chars.offset(), 4); assert_eq!(chars.next(), None); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#125)### impl<'a> Clone for CharIndices<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#125)#### fn clone(&self) -> CharIndices<'a> Notable traits for [CharIndices](struct.charindices "struct std::str::CharIndices")<'a> ``` impl<'a> Iterator for CharIndices<'a> type Item = (usize, char); ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#125)### impl<'a> Debug for CharIndices<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#125)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#169)### impl<'a> DoubleEndedIterator for CharIndices<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#171)#### fn next\_back(&mut self) -> Option<(usize, char)> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#134)### impl<'a> Iterator for CharIndices<'a> #### type Item = (usize, char) The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#138)#### fn next(&mut self) -> Option<(usize, char)> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#152)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#157)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#162)#### fn last(self) -> Option<(usize, char)> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../primitive.reference) T>, P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&](../primitive.reference)T) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)#### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)#### fn cycle(self) -> Cycle<Self>where Self: [Clone](../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#180)1.26.0 · ### impl FusedIterator for CharIndices<'\_> Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for CharIndices<'a> ### impl<'a> Send for CharIndices<'a> ### impl<'a> Sync for CharIndices<'a> ### impl<'a> Unpin for CharIndices<'a> ### impl<'a> UnwindSafe for CharIndices<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::EscapeDebug Struct std::str::EscapeDebug ============================ ``` pub struct EscapeDebug<'a> { /* private fields */ } ``` The return type of [`str::escape_debug`](../primitive.str#method.escape_debug "str::escape_debug"). Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1438)### impl<'a> Clone for EscapeDebug<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1438)#### fn clone(&self) -> EscapeDebug<'a> Notable traits for [EscapeDebug](struct.escapedebug "struct std::str::EscapeDebug")<'a> ``` impl<'a> Iterator for EscapeDebug<'a> type Item = char; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1438)### impl<'a> Debug for EscapeDebug<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1438)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)### impl<'a> Display for EscapeDebug<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)### impl<'a> Iterator for EscapeDebug<'a> #### type Item = char The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn next(&mut self) -> Option<char> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn try\_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> Rwhere Fold: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Acc, <[EscapeDebug](struct.escapedebug "struct std::str::EscapeDebug")<'a> as [Iterator](../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Acc>, [EscapeDebug](struct.escapedebug "struct std::str::EscapeDebug")<'a>: [Sized](../marker/trait.sized "trait std::marker::Sized"), An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Accwhere Fold: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Acc, <[EscapeDebug](struct.escapedebug "struct std::str::EscapeDebug")<'a> as [Iterator](../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Acc, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)1.0.0 · #### fn cycle(self) -> Cycle<Self>where Self: [Clone](../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)### impl<'a> FusedIterator for EscapeDebug<'a> Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for EscapeDebug<'a> ### impl<'a> Send for EscapeDebug<'a> ### impl<'a> Sync for EscapeDebug<'a> ### impl<'a> Unpin for EscapeDebug<'a> ### impl<'a> UnwindSafe for EscapeDebug<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2500)### impl<T> ToString for Twhere T: [Display](../fmt/trait.display "trait std::fmt::Display") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2506)#### default fn to\_string(&self) -> String Converts the given value to a `String`. [Read more](../string/trait.tostring#tymethod.to_string) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::SplitN Struct std::str::SplitN ======================= ``` pub struct SplitN<'a, P>(_)where    P: Pattern<'a>; ``` Created with the method [`splitn`](../primitive.str#method.splitn). Implementations --------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#931)### impl<'a, P> SplitN<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#947)#### pub fn as\_str(&self) -> &'a str 🔬This is a nightly-only experimental API. (`str_split_as_str` [#77998](https://github.com/rust-lang/rust/issues/77998)) Returns remainder of the split string ##### Examples ``` #![feature(str_split_as_str)] let mut split = "Mary had a little lamb".splitn(3, ' '); assert_eq!(split.as_str(), "Mary had a little lamb"); split.next(); assert_eq!(split.as_str(), "had a little lamb"); split.by_ref().for_each(drop); assert_eq!(split.as_str(), ""); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#913-929)### impl<'a, P> Clone for SplitN<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#913-929)#### fn clone(&self) -> SplitN<'a, P> Notable traits for [SplitN](struct.splitn "struct std::str::SplitN")<'a, P> ``` impl<'a, P> Iterator for SplitN<'a, P>where     P: Pattern<'a>, type Item = &'a str; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#913-929)### impl<'a, P> Debug for SplitN<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Debug](../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#913-929)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#913-929)### impl<'a, P> Iterator for SplitN<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, #### type Item = &'a str The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#913-929)#### fn next(&mut self) -> Option<&'a str> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#215)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#913-929)1.26.0 · ### impl<'a, P> FusedIterator for SplitN<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, Auto Trait Implementations -------------------------- ### impl<'a, P> RefUnwindSafe for SplitN<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, P> Send for SplitN<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Send](../marker/trait.send "trait std::marker::Send"), ### impl<'a, P> Sync for SplitN<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, P> Unpin for SplitN<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, P> UnwindSafe for SplitN<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Module std::str Module std::str =============== Utilities for the `str` primitive type. *[See also the `str` primitive type](../primitive.str).* Modules ------- [pattern](pattern/index "std::str::pattern mod")Experimental The string Pattern API. Structs ------- [Utf8Chunk](struct.utf8chunk "std::str::Utf8Chunk struct")Experimental An item returned by the [`Utf8Chunks`](struct.utf8chunks "Utf8Chunks") iterator. [Utf8Chunks](struct.utf8chunks "std::str::Utf8Chunks struct")Experimental An iterator used to decode a slice of mostly UTF-8 bytes to string slices ([`&str`](../primitive.str "&str")) and byte slices ([`&[u8]`](../primitive.slice)). [Bytes](struct.bytes "std::str::Bytes struct") An iterator over the bytes of a string slice. [CharIndices](struct.charindices "std::str::CharIndices struct") An iterator over the [`char`](../primitive.char)s of a string slice, and their positions. [Chars](struct.chars "std::str::Chars struct") An iterator over the [`char`](../primitive.char)s of a string slice. [EncodeUtf16](struct.encodeutf16 "std::str::EncodeUtf16 struct") An iterator of [`u16`](../primitive.u16 "u16") over the string encoded as UTF-16. [EscapeDebug](struct.escapedebug "std::str::EscapeDebug struct") The return type of [`str::escape_debug`](../primitive.str#method.escape_debug "str::escape_debug"). [EscapeDefault](struct.escapedefault "std::str::EscapeDefault struct") The return type of [`str::escape_default`](../primitive.str#method.escape_default "str::escape_default"). [EscapeUnicode](struct.escapeunicode "std::str::EscapeUnicode struct") The return type of [`str::escape_unicode`](../primitive.str#method.escape_unicode "str::escape_unicode"). [Lines](struct.lines "std::str::Lines struct") An iterator over the lines of a string, as string slices. [LinesAny](struct.linesany "std::str::LinesAny struct")Deprecated Created with the method [`lines_any`](../primitive.str#method.lines_any). [MatchIndices](struct.matchindices "std::str::MatchIndices struct") Created with the method [`match_indices`](../primitive.str#method.match_indices). [Matches](struct.matches "std::str::Matches struct") Created with the method [`matches`](../primitive.str#method.matches). [ParseBoolError](struct.parseboolerror "std::str::ParseBoolError struct") An error returned when parsing a `bool` using [`from_str`](trait.fromstr#tymethod.from_str) fails [RMatchIndices](struct.rmatchindices "std::str::RMatchIndices struct") Created with the method [`rmatch_indices`](../primitive.str#method.rmatch_indices). [RMatches](struct.rmatches "std::str::RMatches struct") Created with the method [`rmatches`](../primitive.str#method.rmatches). [RSplit](struct.rsplit "std::str::RSplit struct") Created with the method [`rsplit`](../primitive.str#method.rsplit). [RSplitN](struct.rsplitn "std::str::RSplitN struct") Created with the method [`rsplitn`](../primitive.str#method.rsplitn). [RSplitTerminator](struct.rsplitterminator "std::str::RSplitTerminator struct") Created with the method [`rsplit_terminator`](../primitive.str#method.rsplit_terminator). [Split](struct.split "std::str::Split struct") Created with the method [`split`](../primitive.str#method.split). [SplitAsciiWhitespace](struct.splitasciiwhitespace "std::str::SplitAsciiWhitespace struct") An iterator over the non-ASCII-whitespace substrings of a string, separated by any amount of ASCII whitespace. [SplitInclusive](struct.splitinclusive "std::str::SplitInclusive struct") An iterator over the substrings of a string, terminated by a substring matching to a predicate function Unlike `Split`, it contains the matched part as a terminator of the subslice. [SplitN](struct.splitn "std::str::SplitN struct") Created with the method [`splitn`](../primitive.str#method.splitn). [SplitTerminator](struct.splitterminator "std::str::SplitTerminator struct") Created with the method [`split_terminator`](../primitive.str#method.split_terminator). [SplitWhitespace](struct.splitwhitespace "std::str::SplitWhitespace struct") An iterator over the non-whitespace substrings of a string, separated by any amount of whitespace. [Utf8Error](struct.utf8error "std::str::Utf8Error struct") Errors which can occur when attempting to interpret a sequence of [`u8`](../primitive.u8 "u8") as a string. Traits ------ [FromStr](trait.fromstr "std::str::FromStr trait") Parse a value from a string Functions --------- [from\_boxed\_utf8\_unchecked](fn.from_boxed_utf8_unchecked "std::str::from_boxed_utf8_unchecked fn")[⚠](# "unsafe function") Converts a boxed slice of bytes to a boxed string slice without checking that the string contains valid UTF-8. [from\_utf8](fn.from_utf8 "std::str::from_utf8 fn") Converts a slice of bytes to a string slice. [from\_utf8\_mut](fn.from_utf8_mut "std::str::from_utf8_mut fn") Converts a mutable slice of bytes to a mutable string slice. [from\_utf8\_unchecked](fn.from_utf8_unchecked "std::str::from_utf8_unchecked fn")[⚠](# "unsafe function") Converts a slice of bytes to a string slice without checking that the string contains valid UTF-8. [from\_utf8\_unchecked\_mut](fn.from_utf8_unchecked_mut "std::str::from_utf8_unchecked_mut fn")[⚠](# "unsafe function") Converts a slice of bytes to a string slice without checking that the string contains valid UTF-8; mutable version. rust Struct std::str::Utf8Chunk Struct std::str::Utf8Chunk ========================== ``` pub struct Utf8Chunk<'a> { /* private fields */ } ``` 🔬This is a nightly-only experimental API. (`utf8_chunks` [#99543](https://github.com/rust-lang/rust/issues/99543)) An item returned by the [`Utf8Chunks`](struct.utf8chunks "Utf8Chunks") iterator. A `Utf8Chunk` stores a sequence of [`u8`](../primitive.u8 "u8") up to the first broken character when decoding a UTF-8 string. Examples -------- ``` #![feature(utf8_chunks)] use std::str::Utf8Chunks; // An invalid UTF-8 string let bytes = b"foo\xF1\x80bar"; // Decode the first `Utf8Chunk` let chunk = Utf8Chunks::new(bytes).next().unwrap(); // The first three characters are valid UTF-8 assert_eq!("foo", chunk.valid()); // The fourth character is broken assert_eq!(b"\xF1\x80", chunk.invalid()); ``` Implementations --------------- [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#40)### impl<'a> Utf8Chunk<'a> [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#47)#### pub fn valid(&self) -> &'a str 🔬This is a nightly-only experimental API. (`utf8_chunks` [#99543](https://github.com/rust-lang/rust/issues/99543)) Returns the next validated UTF-8 substring. This substring can be empty at the start of the string or between broken UTF-8 characters. [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#67)#### pub fn invalid(&self) -> &'a [u8] Notable traits for &[[u8](../primitive.u8)] ``` impl Read for &[u8] impl Write for &mut [u8] ``` 🔬This is a nightly-only experimental API. (`utf8_chunks` [#99543](https://github.com/rust-lang/rust/issues/99543)) Returns the invalid sequence that caused a failure. The returned slice will have a maximum length of 3 and starts after the substring given by [`valid`](struct.utf8chunk#method.valid). Decoding will resume after this sequence. If empty, this is the last chunk in the string. If non-empty, an unexpected byte was encountered or the end of the input was reached unexpectedly. Lossy decoding would replace this sequence with [`U+FFFD REPLACEMENT CHARACTER`](../char/constant.replacement_character). Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#34)### impl<'a> Clone for Utf8Chunk<'a> [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#34)#### fn clone(&self) -> Utf8Chunk<'a> Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#34)### impl<'a> Debug for Utf8Chunk<'a> [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#34)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#34)### impl<'a> PartialEq<Utf8Chunk<'a>> for Utf8Chunk<'a> [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#34)#### fn eq(&self, other: &Utf8Chunk<'a>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)1.0.0 · #### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#34)### impl<'a> Eq for Utf8Chunk<'a> [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#34)### impl<'a> StructuralEq for Utf8Chunk<'a> [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#34)### impl<'a> StructuralPartialEq for Utf8Chunk<'a> Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for Utf8Chunk<'a> ### impl<'a> Send for Utf8Chunk<'a> ### impl<'a> Sync for Utf8Chunk<'a> ### impl<'a> Unpin for Utf8Chunk<'a> ### impl<'a> UnwindSafe for Utf8Chunk<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Function std::str::from_utf8_unchecked Function std::str::from\_utf8\_unchecked ======================================== ``` pub const unsafe fn from_utf8_unchecked(v: &[u8]) -> &str ``` Converts a slice of bytes to a string slice without checking that the string contains valid UTF-8. See the safe version, [`from_utf8`](fn.from_utf8 "from_utf8"), for more information. Safety ------ The bytes passed in must be valid UTF-8. Examples -------- Basic usage: ``` use std::str; // some bytes, in a vector let sparkle_heart = vec![240, 159, 146, 150]; let sparkle_heart = unsafe { str::from_utf8_unchecked(&sparkle_heart) }; assert_eq!("💖", sparkle_heart); ``` rust Function std::str::from_utf8_unchecked_mut Function std::str::from\_utf8\_unchecked\_mut ============================================= ``` pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str ``` Converts a slice of bytes to a string slice without checking that the string contains valid UTF-8; mutable version. See the immutable version, [`from_utf8_unchecked()`](fn.from_utf8_unchecked "from_utf8_unchecked()") for more information. Examples -------- Basic usage: ``` use std::str; let mut heart = vec![240, 159, 146, 150]; let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) }; assert_eq!("💖", heart); ``` rust Struct std::str::Bytes Struct std::str::Bytes ====================== ``` pub struct Bytes<'a>(_); ``` An iterator over the bytes of a string slice. This struct is created by the [`bytes`](../primitive.str#method.bytes) method on [`str`](../primitive.str "str"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#228)### impl<'a> Clone for Bytes<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#228)#### fn clone(&self) -> Bytes<'a> Notable traits for [Bytes](struct.bytes "struct std::str::Bytes")<'\_> ``` impl Iterator for Bytes<'_> type Item = u8; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#228)### impl<'a> Debug for Bytes<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#228)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#309)### impl DoubleEndedIterator for Bytes<'\_> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#311)#### fn next\_back(&mut self) -> Option<u8> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#316)#### fn nth\_back(&mut self, n: usize) -> Option<<Bytes<'\_> as Iterator>::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#321-323)#### fn rfind<P>(&mut self, predicate: P) -> Option<<Bytes<'\_> as Iterator>::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&<[Bytes](struct.bytes "struct std::str::Bytes")<'\_> as [Iterator](../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#330)### impl ExactSizeIterator for Bytes<'\_> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#332)#### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#337)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#232)### impl Iterator for Bytes<'\_> #### type Item = u8 The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#236)#### fn next(&mut self) -> Option<u8> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#241)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#246)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#251)#### fn last(self) -> Option<<Bytes<'\_> as Iterator>::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#256)#### fn nth(&mut self, n: usize) -> Option<<Bytes<'\_> as Iterator>::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#261-263)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(<[Bytes](struct.bytes "struct std::str::Bytes")<'\_> as [Iterator](../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#269-271)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(<[Bytes](struct.bytes "struct std::str::Bytes")<'\_> as [Iterator](../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#277-279)#### fn find<P>(&mut self, predicate: P) -> Option<<Bytes<'\_> as Iterator>::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&<[Bytes](struct.bytes "struct std::str::Bytes")<'\_> as [Iterator](../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#285-287)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(<[Bytes](struct.bytes "struct std::str::Bytes")<'\_> as [Iterator](../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#293-295)#### fn rposition<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(<[Bytes](struct.bytes "struct std::str::Bytes")<'\_> as [Iterator](../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator from the right, returning its index. [Read more](../iter/trait.iterator#method.rposition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../primitive.reference) T>, P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&](../primitive.reference)T) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)#### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)#### fn cycle(self) -> Cycle<Self>where Self: [Clone](../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#343)1.26.0 · ### impl FusedIterator for Bytes<'\_> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#346)### impl TrustedLen for Bytes<'\_> Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for Bytes<'a> ### impl<'a> Send for Bytes<'a> ### impl<'a> Sync for Bytes<'a> ### impl<'a> Unpin for Bytes<'a> ### impl<'a> UnwindSafe for Bytes<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::SplitTerminator Struct std::str::SplitTerminator ================================ ``` pub struct SplitTerminator<'a, P>(_)where    P: Pattern<'a>; ``` Created with the method [`split_terminator`](../primitive.str#method.split_terminator). Implementations --------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#808)### impl<'a, P> SplitTerminator<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#824)#### pub fn as\_str(&self) -> &'a str 🔬This is a nightly-only experimental API. (`str_split_as_str` [#77998](https://github.com/rust-lang/rust/issues/77998)) Returns remainder of the split string ##### Examples ``` #![feature(str_split_as_str)] let mut split = "A..B..".split_terminator('.'); assert_eq!(split.as_str(), "A..B.."); split.next(); assert_eq!(split.as_str(), ".B.."); split.by_ref().for_each(drop); assert_eq!(split.as_str(), ""); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)### impl<'a, P> Clone for SplitTerminator<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)#### fn clone(&self) -> SplitTerminator<'a, P> Notable traits for [SplitTerminator](struct.splitterminator "struct std::str::SplitTerminator")<'a, P> ``` impl<'a, P> Iterator for SplitTerminator<'a, P>where     P: Pattern<'a>, type Item = &'a str; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)### impl<'a, P> Debug for SplitTerminator<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Debug](../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)### impl<'a, P> DoubleEndedIterator for SplitTerminator<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [DoubleEndedSearcher](pattern/trait.doubleendedsearcher "trait std::str::pattern::DoubleEndedSearcher")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)#### fn next\_back(&mut self) -> Option<&'a str> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)### impl<'a, P> Iterator for SplitTerminator<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, #### type Item = &'a str The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)#### fn next(&mut self) -> Option<&'a str> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#215)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)1.26.0 · ### impl<'a, P> FusedIterator for SplitTerminator<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, Auto Trait Implementations -------------------------- ### impl<'a, P> RefUnwindSafe for SplitTerminator<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, P> Send for SplitTerminator<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Send](../marker/trait.send "trait std::marker::Send"), ### impl<'a, P> Sync for SplitTerminator<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, P> Unpin for SplitTerminator<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, P> UnwindSafe for SplitTerminator<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::Lines Struct std::str::Lines ====================== ``` pub struct Lines<'a>(_); ``` An iterator over the lines of a string, as string slices. This struct is created with the [`lines`](../primitive.str#method.lines) method on [`str`](../primitive.str "str"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1093)### impl<'a> Clone for Lines<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1093)#### fn clone(&self) -> Lines<'a> Notable traits for [Lines](struct.lines "struct std::str::Lines")<'a> ``` impl<'a> Iterator for Lines<'a> type Item = &'a str; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1093)### impl<'a> Debug for Lines<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1093)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1117)### impl<'a> DoubleEndedIterator for Lines<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1119)#### fn next\_back(&mut self) -> Option<&'a str> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1097)### impl<'a> Iterator for Lines<'a> #### type Item = &'a str The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1101)#### fn next(&mut self) -> Option<&'a str> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1106)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1111)#### fn last(self) -> Option<&'a str> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../primitive.reference) T>, P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&](../primitive.reference)T) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)#### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)#### fn cycle(self) -> Cycle<Self>where Self: [Clone](../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1125)1.26.0 · ### impl FusedIterator for Lines<'\_> Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for Lines<'a> ### impl<'a> Send for Lines<'a> ### impl<'a> Sync for Lines<'a> ### impl<'a> Unpin for Lines<'a> ### impl<'a> UnwindSafe for Lines<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::EncodeUtf16 Struct std::str::EncodeUtf16 ============================ ``` pub struct EncodeUtf16<'a> { /* private fields */ } ``` An iterator of [`u16`](../primitive.u16 "u16") over the string encoded as UTF-16. This struct is created by the [`encode_utf16`](../primitive.str#method.encode_utf16) method on [`str`](../primitive.str "str"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1387)### impl<'a> Clone for EncodeUtf16<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1387)#### fn clone(&self) -> EncodeUtf16<'a> Notable traits for [EncodeUtf16](struct.encodeutf16 "struct std::str::EncodeUtf16")<'a> ``` impl<'a> Iterator for EncodeUtf16<'a> type Item = u16; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1395)1.17.0 · ### impl Debug for EncodeUtf16<'\_> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1396)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1402)### impl<'a> Iterator for EncodeUtf16<'a> #### type Item = u16 The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1406)#### fn next(&mut self) -> Option<u16> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1424)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)1.0.0 · #### fn cycle(self) -> Cycle<Self>where Self: [Clone](../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1434)1.26.0 · ### impl FusedIterator for EncodeUtf16<'\_> Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for EncodeUtf16<'a> ### impl<'a> Send for EncodeUtf16<'a> ### impl<'a> Sync for EncodeUtf16<'a> ### impl<'a> Unpin for EncodeUtf16<'a> ### impl<'a> UnwindSafe for EncodeUtf16<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::SplitWhitespace Struct std::str::SplitWhitespace ================================ ``` pub struct SplitWhitespace<'a> { /* private fields */ } ``` An iterator over the non-whitespace substrings of a string, separated by any amount of whitespace. This struct is created by the [`split_whitespace`](../primitive.str#method.split_whitespace) method on [`str`](../primitive.str "str"). See its documentation for more. Implementations --------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1236)### impl<'a> SplitWhitespace<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1256)#### pub fn as\_str(&self) -> &'a str 🔬This is a nightly-only experimental API. (`str_split_whitespace_as_str` [#77998](https://github.com/rust-lang/rust/issues/77998)) Returns remainder of the split string ##### Examples ``` #![feature(str_split_whitespace_as_str)] let mut split = "Mary had a little lamb".split_whitespace(); assert_eq!(split.as_str(), "Mary had a little lamb"); split.next(); assert_eq!(split.as_str(), "had a little lamb"); split.by_ref().for_each(drop); assert_eq!(split.as_str(), ""); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1174)### impl<'a> Clone for SplitWhitespace<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1174)#### fn clone(&self) -> SplitWhitespace<'a> Notable traits for [SplitWhitespace](struct.splitwhitespace "struct std::str::SplitWhitespace")<'a> ``` impl<'a> Iterator for SplitWhitespace<'a> type Item = &'a str; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1174)### impl<'a> Debug for SplitWhitespace<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1174)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1226)### impl<'a> DoubleEndedIterator for SplitWhitespace<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1228)#### fn next\_back(&mut self) -> Option<&'a str> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1206)### impl<'a> Iterator for SplitWhitespace<'a> #### type Item = &'a str The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1210)#### fn next(&mut self) -> Option<&'a str> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1215)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1220)#### fn last(self) -> Option<&'a str> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../primitive.reference) T>, P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&](../primitive.reference)T) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)1.0.0 · #### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)1.0.0 · #### fn cycle(self) -> Cycle<Self>where Self: [Clone](../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1234)1.26.0 · ### impl FusedIterator for SplitWhitespace<'\_> Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for SplitWhitespace<'a> ### impl<'a> Send for SplitWhitespace<'a> ### impl<'a> Sync for SplitWhitespace<'a> ### impl<'a> Unpin for SplitWhitespace<'a> ### impl<'a> UnwindSafe for SplitWhitespace<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::Split Struct std::str::Split ====================== ``` pub struct Split<'a, P>(_)where    P: Pattern<'a>; ``` Created with the method [`split`](../primitive.str#method.split). Implementations --------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#748)### impl<'a, P> Split<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#764)#### pub fn as\_str(&self) -> &'a str 🔬This is a nightly-only experimental API. (`str_split_as_str` [#77998](https://github.com/rust-lang/rust/issues/77998)) Returns remainder of the split string ##### Examples ``` #![feature(str_split_as_str)] let mut split = "Mary had a little lamb".split(' '); assert_eq!(split.as_str(), "Mary had a little lamb"); split.next(); assert_eq!(split.as_str(), "had a little lamb"); split.by_ref().for_each(drop); assert_eq!(split.as_str(), ""); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)### impl<'a, P> Clone for Split<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)#### fn clone(&self) -> Split<'a, P> Notable traits for [Split](struct.split "struct std::str::Split")<'a, P> ``` impl<'a, P> Iterator for Split<'a, P>where     P: Pattern<'a>, type Item = &'a str; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)### impl<'a, P> Debug for Split<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Debug](../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)### impl<'a, P> DoubleEndedIterator for Split<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [DoubleEndedSearcher](pattern/trait.doubleendedsearcher "trait std::str::pattern::DoubleEndedSearcher")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)#### fn next\_back(&mut self) -> Option<&'a str> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)### impl<'a, P> Iterator for Split<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, #### type Item = &'a str The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)#### fn next(&mut self) -> Option<&'a str> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#215)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)1.26.0 · ### impl<'a, P> FusedIterator for Split<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, Auto Trait Implementations -------------------------- ### impl<'a, P> RefUnwindSafe for Split<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, P> Send for Split<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Send](../marker/trait.send "trait std::marker::Send"), ### impl<'a, P> Sync for Split<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, P> Unpin for Split<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, P> UnwindSafe for Split<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::EscapeUnicode Struct std::str::EscapeUnicode ============================== ``` pub struct EscapeUnicode<'a> { /* private fields */ } ``` The return type of [`str::escape_unicode`](../primitive.str#method.escape_unicode "str::escape_unicode"). Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1455)### impl<'a> Clone for EscapeUnicode<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1455)#### fn clone(&self) -> EscapeUnicode<'a> Notable traits for [EscapeUnicode](struct.escapeunicode "struct std::str::EscapeUnicode")<'a> ``` impl<'a> Iterator for EscapeUnicode<'a> type Item = char; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1455)### impl<'a> Debug for EscapeUnicode<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1455)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)### impl<'a> Display for EscapeUnicode<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)### impl<'a> Iterator for EscapeUnicode<'a> #### type Item = char The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn next(&mut self) -> Option<char> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn try\_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> Rwhere Fold: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Acc, <[EscapeUnicode](struct.escapeunicode "struct std::str::EscapeUnicode")<'a> as [Iterator](../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Acc>, [EscapeUnicode](struct.escapeunicode "struct std::str::EscapeUnicode")<'a>: [Sized](../marker/trait.sized "trait std::marker::Sized"), An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Accwhere Fold: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Acc, <[EscapeUnicode](struct.escapeunicode "struct std::str::EscapeUnicode")<'a> as [Iterator](../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Acc, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)1.0.0 · #### fn cycle(self) -> Cycle<Self>where Self: [Clone](../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)### impl<'a> FusedIterator for EscapeUnicode<'a> Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for EscapeUnicode<'a> ### impl<'a> Send for EscapeUnicode<'a> ### impl<'a> Sync for EscapeUnicode<'a> ### impl<'a> Unpin for EscapeUnicode<'a> ### impl<'a> UnwindSafe for EscapeUnicode<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2500)### impl<T> ToString for Twhere T: [Display](../fmt/trait.display "trait std::fmt::Display") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2506)#### default fn to\_string(&self) -> String Converts the given value to a `String`. [Read more](../string/trait.tostring#tymethod.to_string) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::RMatchIndices Struct std::str::RMatchIndices ============================== ``` pub struct RMatchIndices<'a, P>(_)where    P: Pattern<'a>; ``` Created with the method [`rmatch_indices`](../primitive.str#method.rmatch_indices). Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)### impl<'a, P> Clone for RMatchIndices<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)#### fn clone(&self) -> RMatchIndices<'a, P> Notable traits for [RMatchIndices](struct.rmatchindices "struct std::str::RMatchIndices")<'a, P> ``` impl<'a, P> Iterator for RMatchIndices<'a, P>where     P: Pattern<'a>,     <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, type Item = (usize, &'a str); ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)### impl<'a, P> Debug for RMatchIndices<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Debug](../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)### impl<'a, P> DoubleEndedIterator for RMatchIndices<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [DoubleEndedSearcher](pattern/trait.doubleendedsearcher "trait std::str::pattern::DoubleEndedSearcher")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)#### fn next\_back(&mut self) -> Option<(usize, &'a str)> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)### impl<'a, P> Iterator for RMatchIndices<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [ReverseSearcher](pattern/trait.reversesearcher "trait std::str::pattern::ReverseSearcher")<'a>, #### type Item = (usize, &'a str) The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)#### fn next(&mut self) -> Option<(usize, &'a str)> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#215)1.0.0 · #### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)#### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)#### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)#### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)#### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)#### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)#### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)#### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)1.26.0 · ### impl<'a, P> FusedIterator for RMatchIndices<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [ReverseSearcher](pattern/trait.reversesearcher "trait std::str::pattern::ReverseSearcher")<'a>, Auto Trait Implementations -------------------------- ### impl<'a, P> RefUnwindSafe for RMatchIndices<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, P> Send for RMatchIndices<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Send](../marker/trait.send "trait std::marker::Send"), ### impl<'a, P> Sync for RMatchIndices<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, P> Unpin for RMatchIndices<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, P> UnwindSafe for RMatchIndices<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::LinesAny Struct std::str::LinesAny ========================= ``` pub struct LinesAny<'a>(_); ``` 👎Deprecated since 1.4.0: use lines()/Lines instead now Created with the method [`lines_any`](../primitive.str#method.lines_any). Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1133)### impl<'a> Clone for LinesAny<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1133)#### fn clone(&self) -> LinesAny<'a> Notable traits for [LinesAny](struct.linesany "struct std::str::LinesAny")<'a> ``` impl<'a> Iterator for LinesAny<'a> type Item = &'a str; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1133)### impl<'a> Debug for LinesAny<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1133)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1155)### impl<'a> DoubleEndedIterator for LinesAny<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1157)#### fn next\_back(&mut self) -> Option<&'a str> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1139)### impl<'a> Iterator for LinesAny<'a> #### type Item = &'a str The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1143)#### fn next(&mut self) -> Option<&'a str> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1148)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../primitive.reference) T>, P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&](../primitive.reference)T) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)#### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)#### fn cycle(self) -> Cycle<Self>where Self: [Clone](../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1164)1.26.0 · ### impl FusedIterator for LinesAny<'\_> Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for LinesAny<'a> ### impl<'a> Send for LinesAny<'a> ### impl<'a> Sync for LinesAny<'a> ### impl<'a> Unpin for LinesAny<'a> ### impl<'a> UnwindSafe for LinesAny<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Function std::str::from_boxed_utf8_unchecked Function std::str::from\_boxed\_utf8\_unchecked =============================================== ``` pub unsafe fn from_boxed_utf8_unchecked(    v: Box<[u8], Global>) -> Box<str, Global>ⓘNotable traits for Box<I, A>impl<I, A> Iterator for Box<I, A>where    I: Iterator + ?Sized,    A: Allocator, type Item = <I as Iterator>::Item;impl<F, A> Future for Box<F, A>where    F: Future + Unpin + ?Sized,    A: Allocator + 'static, type Output = <F as Future>::Output;impl<R: Read + ?Sized> Read for Box<R>impl<W: Write + ?Sized> Write for Box<W> ``` Converts a boxed slice of bytes to a boxed string slice without checking that the string contains valid UTF-8. Examples -------- Basic usage: ``` let smile_utf8 = Box::new([226, 152, 186]); let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) }; assert_eq!("☺", &*smile); ``` rust Struct std::str::Utf8Chunks Struct std::str::Utf8Chunks =========================== ``` pub struct Utf8Chunks<'a> { /* private fields */ } ``` 🔬This is a nightly-only experimental API. (`utf8_chunks` [#99543](https://github.com/rust-lang/rust/issues/99543)) An iterator used to decode a slice of mostly UTF-8 bytes to string slices ([`&str`](../primitive.str "&str")) and byte slices ([`&[u8]`](../primitive.slice)). If you want a simple conversion from UTF-8 byte slices to string slices, [`from_utf8`](fn.from_utf8) is easier to use. Examples -------- This can be used to create functionality similar to [`String::from_utf8_lossy`](../string/struct.string#method.from_utf8_lossy) without allocating heap memory: ``` #![feature(utf8_chunks)] use std::str::Utf8Chunks; fn from_utf8_lossy<F>(input: &[u8], mut push: F) where F: FnMut(&str) { for chunk in Utf8Chunks::new(input) { push(chunk.valid()); if !chunk.invalid().is_empty() { push("\u{FFFD}"); } } } ``` Implementations --------------- [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#149)### impl<'a> Utf8Chunks<'a> [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#152)#### pub fn new(bytes: &'a [u8]) -> Utf8Chunks<'a> Notable traits for [Utf8Chunks](struct.utf8chunks "struct std::str::Utf8Chunks")<'a> ``` impl<'a> Iterator for Utf8Chunks<'a> type Item = Utf8Chunk<'a>; ``` 🔬This is a nightly-only experimental API. (`utf8_chunks` [#99543](https://github.com/rust-lang/rust/issues/99543)) Creates a new iterator to decode the bytes. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#144)### impl<'a> Clone for Utf8Chunks<'a> [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#144)#### fn clone(&self) -> Utf8Chunks<'a> Notable traits for [Utf8Chunks](struct.utf8chunks "struct std::str::Utf8Chunks")<'a> ``` impl<'a> Iterator for Utf8Chunks<'a> type Item = Utf8Chunk<'a>; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#266)### impl Debug for Utf8Chunks<'\_> [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#267)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#164)### impl<'a> Iterator for Utf8Chunks<'a> #### type Item = Utf8Chunk<'a> The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#167)#### fn next(&mut self) -> Option<Utf8Chunk<'a>> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#215)1.0.0 · #### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)1.0.0 · #### fn cycle(self) -> Cycle<Self>where Self: [Clone](../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#263)### impl FusedIterator for Utf8Chunks<'\_> Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for Utf8Chunks<'a> ### impl<'a> Send for Utf8Chunks<'a> ### impl<'a> Sync for Utf8Chunks<'a> ### impl<'a> Unpin for Utf8Chunks<'a> ### impl<'a> UnwindSafe for Utf8Chunks<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::Utf8Error Struct std::str::Utf8Error ========================== ``` pub struct Utf8Error { /* private fields */ } ``` Errors which can occur when attempting to interpret a sequence of [`u8`](../primitive.u8 "u8") as a string. As such, the `from_utf8` family of functions and methods for both [`String`](../string/struct.string#method.from_utf8)s and [`&str`](fn.from_utf8)s make use of this error, for example. Examples -------- This error type’s methods can be used to create functionality similar to `String::from_utf8_lossy` without allocating heap memory: ``` fn from_utf8_lossy<F>(mut input: &[u8], mut push: F) where F: FnMut(&str) { loop { match std::str::from_utf8(input) { Ok(valid) => { push(valid); break } Err(error) => { let (valid, after_valid) = input.split_at(error.valid_up_to()); unsafe { push(std::str::from_utf8_unchecked(valid)) } push("\u{FFFD}"); if let Some(invalid_sequence_length) = error.error_len() { input = &after_valid[invalid_sequence_length..] } else { break } } } } } ``` Implementations --------------- [source](https://doc.rust-lang.org/src/core/str/error.rs.html#53)### impl Utf8Error [source](https://doc.rust-lang.org/src/core/str/error.rs.html#80)1.5.0 (const: 1.63.0) · #### pub const fn valid\_up\_to(&self) -> usize Returns the index in the given string up to which valid UTF-8 was verified. It is the maximum index such that `from_utf8(&input[..index])` would return `Ok(_)`. ##### Examples Basic usage: ``` use std::str; // some invalid bytes, in a vector let sparkle_heart = vec![0, 159, 146, 150]; // std::str::from_utf8 returns a Utf8Error let error = str::from_utf8(&sparkle_heart).unwrap_err(); // the second byte is invalid here assert_eq!(1, error.valid_up_to()); ``` [source](https://doc.rust-lang.org/src/core/str/error.rs.html#103)1.20.0 (const: 1.63.0) · #### pub const fn error\_len(&self) -> Option<usize> Provides more information about the failure: * `None`: the end of the input was reached unexpectedly. `self.valid_up_to()` is 1 to 3 bytes from the end of the input. If a byte stream (such as a file or a network socket) is being decoded incrementally, this could be a valid `char` whose UTF-8 byte sequence is spanning multiple chunks. * `Some(len)`: an unexpected byte was encountered. The length provided is that of the invalid byte sequence that starts at the index given by `valid_up_to()`. Decoding should resume after that sequence (after inserting a [`U+FFFD REPLACEMENT CHARACTER`](../char/constant.replacement_character)) in case of lossy decoding. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/error.rs.html#46)### impl Clone for Utf8Error [source](https://doc.rust-lang.org/src/core/str/error.rs.html#46)#### fn clone(&self) -> Utf8Error Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/error.rs.html#46)### impl Debug for Utf8Error [source](https://doc.rust-lang.org/src/core/str/error.rs.html#46)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/error.rs.html#113)### impl Display for Utf8Error [source](https://doc.rust-lang.org/src/core/str/error.rs.html#114)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/error.rs.html#129)### impl Error for Utf8Error [source](https://doc.rust-lang.org/src/core/str/error.rs.html#131)#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to\_string() [Read more](../error/trait.error#method.description) [source](https://doc.rust-lang.org/src/core/error.rs.html#83)1.30.0 · #### fn source(&self) -> Option<&(dyn Error + 'static)> The lower-level source of this error, if any. [Read more](../error/trait.error#method.source) [source](https://doc.rust-lang.org/src/core/error.rs.html#119)#### fn cause(&self) -> Option<&dyn Error> 👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting [source](https://doc.rust-lang.org/src/core/error.rs.html#193)#### fn provide(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301)) Provides type based access to context intended for error reports. [Read more](../error/trait.error#method.provide) [source](https://doc.rust-lang.org/src/core/str/error.rs.html#46)### impl PartialEq<Utf8Error> for Utf8Error [source](https://doc.rust-lang.org/src/core/str/error.rs.html#46)#### fn eq(&self, other: &Utf8Error) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/core/str/error.rs.html#46)### impl Copy for Utf8Error [source](https://doc.rust-lang.org/src/core/str/error.rs.html#46)### impl Eq for Utf8Error [source](https://doc.rust-lang.org/src/core/str/error.rs.html#46)### impl StructuralEq for Utf8Error [source](https://doc.rust-lang.org/src/core/str/error.rs.html#46)### impl StructuralPartialEq for Utf8Error Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for Utf8Error ### impl Send for Utf8Error ### impl Sync for Utf8Error ### impl Unpin for Utf8Error ### impl UnwindSafe for Utf8Error Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/error.rs.html#197)### impl<E> Provider for Ewhere E: [Error](../error/trait.error "trait std::error::Error") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/error.rs.html#201)#### fn provide(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`provide_any` [#96024](https://github.com/rust-lang/rust/issues/96024)) Data providers should implement this method to provide *all* values they are able to provide by using `demand`. [Read more](../any/trait.provider#tymethod.provide) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2500)### impl<T> ToString for Twhere T: [Display](../fmt/trait.display "trait std::fmt::Display") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2506)#### default fn to\_string(&self) -> String Converts the given value to a `String`. [Read more](../string/trait.tostring#tymethod.to_string) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Struct std::str::SplitInclusive Struct std::str::SplitInclusive =============================== ``` pub struct SplitInclusive<'a, P>(_)where    P: Pattern<'a>; ``` An iterator over the substrings of a string, terminated by a substring matching to a predicate function Unlike `Split`, it contains the matched part as a terminator of the subslice. This struct is created by the [`split_inclusive`](../primitive.str#method.split_inclusive) method on [`str`](../primitive.str "str"). See its documentation for more. Implementations --------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1360)### impl<'a, P> SplitInclusive<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1376)#### pub fn as\_str(&self) -> &'a str 🔬This is a nightly-only experimental API. (`str_split_inclusive_as_str` [#77998](https://github.com/rust-lang/rust/issues/77998)) Returns remainder of the split string ##### Examples ``` #![feature(str_split_inclusive_as_str)] let mut split = "Mary had a little lamb".split_inclusive(' '); assert_eq!(split.as_str(), "Mary had a little lamb"); split.next(); assert_eq!(split.as_str(), "had a little lamb"); split.by_ref().for_each(drop); assert_eq!(split.as_str(), ""); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1341)### impl<'a, P> Clone for SplitInclusive<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1342)#### fn clone(&self) -> SplitInclusive<'a, P> Notable traits for [SplitInclusive](struct.splitinclusive "struct std::str::SplitInclusive")<'a, P> ``` impl<'a, P> Iterator for SplitInclusive<'a, P>where     P: Pattern<'a>, type Item = &'a str; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1333)### impl<'a, P> Debug for SplitInclusive<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Debug](../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1334)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1348-1349)### impl<'a, P> DoubleEndedIterator for SplitInclusive<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [ReverseSearcher](pattern/trait.reversesearcher "trait std::str::pattern::ReverseSearcher")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1352)#### fn next\_back(&mut self) -> Option<&'a str> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1323)### impl<'a, P> Iterator for SplitInclusive<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, #### type Item = &'a str The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1327)#### fn next(&mut self) -> Option<&'a str> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#215)1.0.0 · #### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)#### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1358)### impl<'a, P> FusedIterator for SplitInclusive<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, Auto Trait Implementations -------------------------- ### impl<'a, P> RefUnwindSafe for SplitInclusive<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, P> Send for SplitInclusive<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Send](../marker/trait.send "trait std::marker::Send"), ### impl<'a, P> Sync for SplitInclusive<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, P> Unpin for SplitInclusive<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, P> UnwindSafe for SplitInclusive<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Trait std::str::FromStr Trait std::str::FromStr ======================= ``` pub trait FromStr { type Err; fn from_str(s: &str) -> Result<Self, Self::Err>; } ``` Parse a value from a string `FromStr`’s [`from_str`](trait.fromstr#tymethod.from_str) method is often used implicitly, through [`str`](../primitive.str "str")’s [`parse`](../primitive.str#method.parse) method. See [`parse`](../primitive.str#method.parse)’s documentation for examples. `FromStr` does not have a lifetime parameter, and so you can only parse types that do not contain a lifetime parameter themselves. In other words, you can parse an `i32` with `FromStr`, but not a `&i32`. You can parse a struct that contains an `i32`, but not one that contains an `&i32`. Examples -------- Basic implementation of `FromStr` on an example `Point` type: ``` use std::str::FromStr; use std::num::ParseIntError; #[derive(Debug, PartialEq)] struct Point { x: i32, y: i32 } impl FromStr for Point { type Err = ParseIntError; fn from_str(s: &str) -> Result<Self, Self::Err> { let (x, y) = s .strip_prefix('(') .and_then(|s| s.strip_suffix(')')) .and_then(|s| s.split_once(',')) .unwrap(); let x_fromstr = x.parse::<i32>()?; let y_fromstr = y.parse::<i32>()?; Ok(Point { x: x_fromstr, y: y_fromstr }) } } let expected = Ok(Point { x: 1, y: 2 }); // Explicit call assert_eq!(Point::from_str("(1,2)"), expected); // Implicit calls, through parse assert_eq!("(1,2)".parse(), expected); assert_eq!("(1,2)".parse::<Point>(), expected); ``` Required Associated Types ------------------------- [source](https://doc.rust-lang.org/src/core/str/traits.rs.html#546)#### type Err The associated error which can be returned from parsing. Required Methods ---------------- [source](https://doc.rust-lang.org/src/core/str/traits.rs.html#567)#### fn from\_str(s: &str) -> Result<Self, Self::Err> Parses a string `s` to return a value of this type. If parsing succeeds, return the value inside [`Ok`](../result/enum.result#variant.Ok "Ok"), otherwise when the string is ill-formatted return an error specific to the inside [`Err`](../result/enum.result#variant.Err "Err"). The error type is specific to the implementation of the trait. ##### Examples Basic usage with [`i32`](../primitive.i32 "i32"), a type that implements `FromStr`: ``` use std::str::FromStr; let s = "5"; let x = i32::from_str(s).unwrap(); assert_eq!(5, x); ``` Implementors ------------ [source](https://doc.rust-lang.org/src/std/net/parser.rs.html#297-302)1.7.0 · ### impl FromStr for IpAddr #### type Err = AddrParseError [source](https://doc.rust-lang.org/src/std/net/parser.rs.html#434-439)### impl FromStr for SocketAddr #### type Err = AddrParseError [source](https://doc.rust-lang.org/src/core/str/traits.rs.html#571)### impl FromStr for bool #### type Err = ParseBoolError [source](https://doc.rust-lang.org/src/core/char/convert.rs.html#183)1.20.0 · ### impl FromStr for char #### type Err = ParseCharError [source](https://doc.rust-lang.org/src/core/num/dec2flt/mod.rs.html#156)### impl FromStr for f32 #### type Err = ParseFloatError [source](https://doc.rust-lang.org/src/core/num/dec2flt/mod.rs.html#157)### impl FromStr for f64 #### type Err = ParseFloatError [source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1018)### impl FromStr for i8 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1018)### impl FromStr for i16 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1018)### impl FromStr for i32 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1018)### impl FromStr for i64 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1018)### impl FromStr for i128 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1018)### impl FromStr for isize #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1018)### impl FromStr for u8 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1018)### impl FromStr for u16 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1018)### impl FromStr for u32 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1018)### impl FromStr for u64 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1018)### impl FromStr for u128 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1018)### impl FromStr for usize #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1356-1363)1.45.0 · ### impl FromStr for OsString #### type Err = Infallible [source](https://doc.rust-lang.org/src/std/net/parser.rs.html#328-333)### impl FromStr for Ipv4Addr #### type Err = AddrParseError [source](https://doc.rust-lang.org/src/std/net/parser.rs.html#354-359)### impl FromStr for Ipv6Addr #### type Err = AddrParseError [source](https://doc.rust-lang.org/src/std/net/parser.rs.html#380-385)1.5.0 · ### impl FromStr for SocketAddrV4 #### type Err = AddrParseError [source](https://doc.rust-lang.org/src/std/net/parser.rs.html#406-411)1.5.0 · ### impl FromStr for SocketAddrV6 #### type Err = AddrParseError [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#191-192)1.35.0 · ### impl FromStr for NonZeroI8 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#191-192)1.35.0 · ### impl FromStr for NonZeroI16 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#191-192)1.35.0 · ### impl FromStr for NonZeroI32 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#191-192)1.35.0 · ### impl FromStr for NonZeroI64 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#191-192)1.35.0 · ### impl FromStr for NonZeroI128 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#191-192)1.35.0 · ### impl FromStr for NonZeroIsize #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#191-192)1.35.0 · ### impl FromStr for NonZeroU8 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#191-192)1.35.0 · ### impl FromStr for NonZeroU16 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#191-192)1.35.0 · ### impl FromStr for NonZeroU32 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#191-192)1.35.0 · ### impl FromStr for NonZeroU64 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#191-192)1.35.0 · ### impl FromStr for NonZeroU128 #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#191-192)1.35.0 · ### impl FromStr for NonZeroUsize #### type Err = ParseIntError [source](https://doc.rust-lang.org/src/std/path.rs.html#1681-1688)1.32.0 · ### impl FromStr for PathBuf #### type Err = Infallible [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2456)### impl FromStr for String #### type Err = Infallible rust Struct std::str::MatchIndices Struct std::str::MatchIndices ============================= ``` pub struct MatchIndices<'a, P>(_)where    P: Pattern<'a>; ``` Created with the method [`match_indices`](../primitive.str#method.match_indices). Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)### impl<'a, P> Clone for MatchIndices<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)#### fn clone(&self) -> MatchIndices<'a, P> Notable traits for [MatchIndices](struct.matchindices "struct std::str::MatchIndices")<'a, P> ``` impl<'a, P> Iterator for MatchIndices<'a, P>where     P: Pattern<'a>, type Item = (usize, &'a str); ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)### impl<'a, P> Debug for MatchIndices<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Debug](../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)### impl<'a, P> DoubleEndedIterator for MatchIndices<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [DoubleEndedSearcher](pattern/trait.doubleendedsearcher "trait std::str::pattern::DoubleEndedSearcher")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)#### fn next\_back(&mut self) -> Option<(usize, &'a str)> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)### impl<'a, P> Iterator for MatchIndices<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, #### type Item = (usize, &'a str) The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)#### fn next(&mut self) -> Option<(usize, &'a str)> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#215)1.0.0 · #### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)#### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)#### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)#### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)#### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)#### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)#### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)#### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1010-1026)1.26.0 · ### impl<'a, P> FusedIterator for MatchIndices<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, Auto Trait Implementations -------------------------- ### impl<'a, P> RefUnwindSafe for MatchIndices<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, P> Send for MatchIndices<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Send](../marker/trait.send "trait std::marker::Send"), ### impl<'a, P> Sync for MatchIndices<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, P> Unpin for MatchIndices<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, P> UnwindSafe for MatchIndices<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Function std::str::from_utf8_mut Function std::str::from\_utf8\_mut ================================== ``` pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> ``` Converts a mutable slice of bytes to a mutable string slice. Examples -------- Basic usage: ``` use std::str; // "Hello, Rust!" as a mutable vector let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33]; // As we know these bytes are valid, we can use `unwrap()` let outstr = str::from_utf8_mut(&mut hellorust).unwrap(); assert_eq!("Hello, Rust!", outstr); ``` Incorrect bytes: ``` use std::str; // Some invalid bytes in a mutable vector let mut invalid = vec![128, 223]; assert!(str::from_utf8_mut(&mut invalid).is_err()); ``` See the docs for [`Utf8Error`](struct.utf8error "Utf8Error") for more details on the kinds of errors that can be returned. rust Struct std::str::Chars Struct std::str::Chars ====================== ``` pub struct Chars<'a> { /* private fields */ } ``` An iterator over the [`char`](../primitive.char)s of a string slice. This struct is created by the [`chars`](../primitive.str#method.chars) method on [`str`](../primitive.str "str"). See its documentation for more. Implementations --------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#91)### impl<'a> Chars<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#112)1.4.0 · #### pub fn as\_str(&self) -> &'a str Views the underlying data as a subslice of the original data. This has the same lifetime as the original slice, and so the iterator can continue to be used while this exists. ##### Examples ``` let mut chars = "abc".chars(); assert_eq!(chars.as_str(), "abc"); chars.next(); assert_eq!(chars.as_str(), "bc"); chars.next(); chars.next(); assert_eq!(chars.as_str(), ""); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#29)### impl<'a> Clone for Chars<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#29)#### fn clone(&self) -> Chars<'a> Notable traits for [Chars](struct.chars "struct std::str::Chars")<'a> ``` impl<'a> Iterator for Chars<'a> type Item = char; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#69)1.38.0 · ### impl Debug for Chars<'\_> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#70)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#79)### impl<'a> DoubleEndedIterator for Chars<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#81)#### fn next\_back(&mut self) -> Option<char> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#37)### impl<'a> Iterator for Chars<'a> #### type Item = char The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#41)#### fn next(&mut self) -> Option<char> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#48)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#53)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#62)#### fn last(self) -> Option<char> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2082)#### fn partition\_in\_place<'a, T, P>(self, predicate: P) -> usizewhere T: 'a, Self: [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator")<Item = [&'a mut](../primitive.reference) T>, P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&](../primitive.reference)T) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_partition_in_place` [#62543](https://github.com/rust-lang/rust/issues/62543)) Reorders the elements of this iterator *in-place* according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. [Read more](../iter/trait.iterator#method.partition_in_place) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3161-3163)#### fn rev(self) -> Rev<Self>where Self: [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), Notable traits for [Rev](../iter/struct.rev "struct std::iter::Rev")<I> ``` impl<I> Iterator for Rev<I>where     I: DoubleEndedIterator, type Item = <I as Iterator>::Item; ``` Reverses an iterator’s direction. [Read more](../iter/trait.iterator#method.rev) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)#### fn cycle(self) -> Cycle<Self>where Self: [Clone](../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#89)1.26.0 · ### impl FusedIterator for Chars<'\_> Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for Chars<'a> ### impl<'a> Send for Chars<'a> ### impl<'a> Sync for Chars<'a> ### impl<'a> Unpin for Chars<'a> ### impl<'a> UnwindSafe for Chars<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::RSplitN Struct std::str::RSplitN ======================== ``` pub struct RSplitN<'a, P>(_)where    P: Pattern<'a>; ``` Created with the method [`rsplitn`](../primitive.str#method.rsplitn). Implementations --------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#952)### impl<'a, P> RSplitN<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#968)#### pub fn as\_str(&self) -> &'a str 🔬This is a nightly-only experimental API. (`str_split_as_str` [#77998](https://github.com/rust-lang/rust/issues/77998)) Returns remainder of the split string ##### Examples ``` #![feature(str_split_as_str)] let mut split = "Mary had a little lamb".rsplitn(3, ' '); assert_eq!(split.as_str(), "Mary had a little lamb"); split.next(); assert_eq!(split.as_str(), "Mary had a little"); split.by_ref().for_each(drop); assert_eq!(split.as_str(), ""); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#913-929)### impl<'a, P> Clone for RSplitN<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#913-929)#### fn clone(&self) -> RSplitN<'a, P> Notable traits for [RSplitN](struct.rsplitn "struct std::str::RSplitN")<'a, P> ``` impl<'a, P> Iterator for RSplitN<'a, P>where     P: Pattern<'a>,     <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, type Item = &'a str; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#913-929)### impl<'a, P> Debug for RSplitN<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Debug](../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#913-929)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#913-929)### impl<'a, P> Iterator for RSplitN<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [ReverseSearcher](pattern/trait.reversesearcher "trait std::str::pattern::ReverseSearcher")<'a>, #### type Item = &'a str The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#913-929)#### fn next(&mut self) -> Option<&'a str> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#215)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#913-929)1.26.0 · ### impl<'a, P> FusedIterator for RSplitN<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [ReverseSearcher](pattern/trait.reversesearcher "trait std::str::pattern::ReverseSearcher")<'a>, Auto Trait Implementations -------------------------- ### impl<'a, P> RefUnwindSafe for RSplitN<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, P> Send for RSplitN<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Send](../marker/trait.send "trait std::marker::Send"), ### impl<'a, P> Sync for RSplitN<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, P> Unpin for RSplitN<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, P> UnwindSafe for RSplitN<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::Matches Struct std::str::Matches ======================== ``` pub struct Matches<'a, P>(_)where    P: Pattern<'a>; ``` Created with the method [`matches`](../primitive.str#method.matches). Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)### impl<'a, P> Clone for Matches<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)#### fn clone(&self) -> Matches<'a, P> Notable traits for [Matches](struct.matches "struct std::str::Matches")<'a, P> ``` impl<'a, P> Iterator for Matches<'a, P>where     P: Pattern<'a>, type Item = &'a str; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)### impl<'a, P> Debug for Matches<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Debug](../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)### impl<'a, P> DoubleEndedIterator for Matches<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [DoubleEndedSearcher](pattern/trait.doubleendedsearcher "trait std::str::pattern::DoubleEndedSearcher")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)#### fn next\_back(&mut self) -> Option<&'a str> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)### impl<'a, P> Iterator for Matches<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, #### type Item = &'a str The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)#### fn next(&mut self) -> Option<&'a str> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#215)1.0.0 · #### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)1.26.0 · ### impl<'a, P> FusedIterator for Matches<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, Auto Trait Implementations -------------------------- ### impl<'a, P> RefUnwindSafe for Matches<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, P> Send for Matches<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Send](../marker/trait.send "trait std::marker::Send"), ### impl<'a, P> Sync for Matches<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, P> Unpin for Matches<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, P> UnwindSafe for Matches<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::ParseBoolError Struct std::str::ParseBoolError =============================== ``` #[non_exhaustive]pub struct ParseBoolError; ``` An error returned when parsing a `bool` using [`from_str`](trait.fromstr#tymethod.from_str) fails Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/error.rs.html#139)### impl Clone for ParseBoolError [source](https://doc.rust-lang.org/src/core/str/error.rs.html#139)#### fn clone(&self) -> ParseBoolError Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/error.rs.html#139)### impl Debug for ParseBoolError [source](https://doc.rust-lang.org/src/core/str/error.rs.html#139)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/error.rs.html#145)### impl Display for ParseBoolError [source](https://doc.rust-lang.org/src/core/str/error.rs.html#146)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/error.rs.html#153)### impl Error for ParseBoolError [source](https://doc.rust-lang.org/src/core/str/error.rs.html#155)#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to\_string() [Read more](../error/trait.error#method.description) [source](https://doc.rust-lang.org/src/core/error.rs.html#83)1.30.0 · #### fn source(&self) -> Option<&(dyn Error + 'static)> The lower-level source of this error, if any. [Read more](../error/trait.error#method.source) [source](https://doc.rust-lang.org/src/core/error.rs.html#119)#### fn cause(&self) -> Option<&dyn Error> 👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting [source](https://doc.rust-lang.org/src/core/error.rs.html#193)#### fn provide(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301)) Provides type based access to context intended for error reports. [Read more](../error/trait.error#method.provide) [source](https://doc.rust-lang.org/src/core/str/error.rs.html#139)### impl PartialEq<ParseBoolError> for ParseBoolError [source](https://doc.rust-lang.org/src/core/str/error.rs.html#139)#### fn eq(&self, other: &ParseBoolError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/core/str/error.rs.html#139)### impl Eq for ParseBoolError [source](https://doc.rust-lang.org/src/core/str/error.rs.html#139)### impl StructuralEq for ParseBoolError [source](https://doc.rust-lang.org/src/core/str/error.rs.html#139)### impl StructuralPartialEq for ParseBoolError Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for ParseBoolError ### impl Send for ParseBoolError ### impl Sync for ParseBoolError ### impl Unpin for ParseBoolError ### impl UnwindSafe for ParseBoolError Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/error.rs.html#197)### impl<E> Provider for Ewhere E: [Error](../error/trait.error "trait std::error::Error") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/error.rs.html#201)#### fn provide(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`provide_any` [#96024](https://github.com/rust-lang/rust/issues/96024)) Data providers should implement this method to provide *all* values they are able to provide by using `demand`. [Read more](../any/trait.provider#tymethod.provide) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2500)### impl<T> ToString for Twhere T: [Display](../fmt/trait.display "trait std::fmt::Display") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2506)#### default fn to\_string(&self) -> String Converts the given value to a `String`. [Read more](../string/trait.tostring#tymethod.to_string) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Function std::str::from_utf8 Function std::str::from\_utf8 ============================= ``` pub const fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> ``` Converts a slice of bytes to a string slice. A string slice ([`&str`](../primitive.str)) is made of bytes ([`u8`](../primitive.u8 "u8")), and a byte slice ([`&[u8]`](../primitive.slice)) is made of bytes, so this function converts between the two. Not all byte slices are valid string slices, however: [`&str`](../primitive.str) requires that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid UTF-8, and then does the conversion. If you are sure that the byte slice is valid UTF-8, and you don’t want to incur the overhead of the validity check, there is an unsafe version of this function, [`from_utf8_unchecked`](fn.from_utf8_unchecked "from_utf8_unchecked"), which has the same behavior but skips the check. If you need a `String` instead of a `&str`, consider [`String::from_utf8`](../string/struct.string#method.from_utf8). Because you can stack-allocate a `[u8; N]`, and you can take a [`&[u8]`](../primitive.slice) of it, this function is one way to have a stack-allocated string. There is an example of this in the examples section below. Errors ------ Returns `Err` if the slice is not UTF-8 with a description as to why the provided slice is not UTF-8. Examples -------- Basic usage: ``` use std::str; // some bytes, in a vector let sparkle_heart = vec![240, 159, 146, 150]; // We know these bytes are valid, so just use `unwrap()`. let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap(); assert_eq!("💖", sparkle_heart); ``` Incorrect bytes: ``` use std::str; // some invalid bytes, in a vector let sparkle_heart = vec![0, 159, 146, 150]; assert!(str::from_utf8(&sparkle_heart).is_err()); ``` See the docs for [`Utf8Error`](struct.utf8error "Utf8Error") for more details on the kinds of errors that can be returned. A “stack allocated string”: ``` use std::str; // some bytes, in a stack-allocated array let sparkle_heart = [240, 159, 146, 150]; // We know these bytes are valid, so just use `unwrap()`. let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap(); assert_eq!("💖", sparkle_heart); ``` rust Struct std::str::RSplitTerminator Struct std::str::RSplitTerminator ================================= ``` pub struct RSplitTerminator<'a, P>(_)where    P: Pattern<'a>; ``` Created with the method [`rsplit_terminator`](../primitive.str#method.rsplit_terminator). Implementations --------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#829)### impl<'a, P> RSplitTerminator<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#845)#### pub fn as\_str(&self) -> &'a str 🔬This is a nightly-only experimental API. (`str_split_as_str` [#77998](https://github.com/rust-lang/rust/issues/77998)) Returns remainder of the split string ##### Examples ``` #![feature(str_split_as_str)] let mut split = "A..B..".rsplit_terminator('.'); assert_eq!(split.as_str(), "A..B.."); split.next(); assert_eq!(split.as_str(), "A..B"); split.by_ref().for_each(drop); assert_eq!(split.as_str(), ""); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)### impl<'a, P> Clone for RSplitTerminator<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)#### fn clone(&self) -> RSplitTerminator<'a, P> Notable traits for [RSplitTerminator](struct.rsplitterminator "struct std::str::RSplitTerminator")<'a, P> ``` impl<'a, P> Iterator for RSplitTerminator<'a, P>where     P: Pattern<'a>,     <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, type Item = &'a str; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)### impl<'a, P> Debug for RSplitTerminator<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Debug](../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)### impl<'a, P> DoubleEndedIterator for RSplitTerminator<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [DoubleEndedSearcher](pattern/trait.doubleendedsearcher "trait std::str::pattern::DoubleEndedSearcher")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)#### fn next\_back(&mut self) -> Option<&'a str> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)### impl<'a, P> Iterator for RSplitTerminator<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [ReverseSearcher](pattern/trait.reversesearcher "trait std::str::pattern::ReverseSearcher")<'a>, #### type Item = &'a str The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)#### fn next(&mut self) -> Option<&'a str> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#215)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#790-806)1.26.0 · ### impl<'a, P> FusedIterator for RSplitTerminator<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [ReverseSearcher](pattern/trait.reversesearcher "trait std::str::pattern::ReverseSearcher")<'a>, Auto Trait Implementations -------------------------- ### impl<'a, P> RefUnwindSafe for RSplitTerminator<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, P> Send for RSplitTerminator<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Send](../marker/trait.send "trait std::marker::Send"), ### impl<'a, P> Sync for RSplitTerminator<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, P> Unpin for RSplitTerminator<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, P> UnwindSafe for RSplitTerminator<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::RMatches Struct std::str::RMatches ========================= ``` pub struct RMatches<'a, P>(_)where    P: Pattern<'a>; ``` Created with the method [`rmatches`](../primitive.str#method.rmatches). Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)### impl<'a, P> Clone for RMatches<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)#### fn clone(&self) -> RMatches<'a, P> Notable traits for [RMatches](struct.rmatches "struct std::str::RMatches")<'a, P> ``` impl<'a, P> Iterator for RMatches<'a, P>where     P: Pattern<'a>,     <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, type Item = &'a str; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)### impl<'a, P> Debug for RMatches<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Debug](../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)### impl<'a, P> DoubleEndedIterator for RMatches<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [DoubleEndedSearcher](pattern/trait.doubleendedsearcher "trait std::str::pattern::DoubleEndedSearcher")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)#### fn next\_back(&mut self) -> Option<&'a str> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)### impl<'a, P> Iterator for RMatches<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [ReverseSearcher](pattern/trait.reversesearcher "trait std::str::pattern::ReverseSearcher")<'a>, #### type Item = &'a str The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)#### fn next(&mut self) -> Option<&'a str> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#215)1.0.0 · #### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1067-1083)1.26.0 · ### impl<'a, P> FusedIterator for RMatches<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [ReverseSearcher](pattern/trait.reversesearcher "trait std::str::pattern::ReverseSearcher")<'a>, Auto Trait Implementations -------------------------- ### impl<'a, P> RefUnwindSafe for RMatches<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, P> Send for RMatches<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Send](../marker/trait.send "trait std::marker::Send"), ### impl<'a, P> Sync for RMatches<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, P> Unpin for RMatches<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, P> UnwindSafe for RMatches<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::RSplit Struct std::str::RSplit ======================= ``` pub struct RSplit<'a, P>(_)where    P: Pattern<'a>; ``` Created with the method [`rsplit`](../primitive.str#method.rsplit). Implementations --------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#769)### impl<'a, P> RSplit<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#785)#### pub fn as\_str(&self) -> &'a str 🔬This is a nightly-only experimental API. (`str_split_as_str` [#77998](https://github.com/rust-lang/rust/issues/77998)) Returns remainder of the split string ##### Examples ``` #![feature(str_split_as_str)] let mut split = "Mary had a little lamb".rsplit(' '); assert_eq!(split.as_str(), "Mary had a little lamb"); split.next(); assert_eq!(split.as_str(), "Mary had a little"); split.by_ref().for_each(drop); assert_eq!(split.as_str(), ""); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)### impl<'a, P> Clone for RSplit<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)#### fn clone(&self) -> RSplit<'a, P> Notable traits for [RSplit](struct.rsplit "struct std::str::RSplit")<'a, P> ``` impl<'a, P> Iterator for RSplit<'a, P>where     P: Pattern<'a>,     <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, type Item = &'a str; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)### impl<'a, P> Debug for RSplit<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Debug](../fmt/trait.debug "trait std::fmt::Debug"), [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)### impl<'a, P> DoubleEndedIterator for RSplit<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [DoubleEndedSearcher](pattern/trait.doubleendedsearcher "trait std::str::pattern::DoubleEndedSearcher")<'a>, [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)#### fn next\_back(&mut self) -> Option<&'a str> Removes and returns an element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#134)#### fn advance\_back\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator from the back by `n` elements. [Read more](../iter/trait.doubleendediterator#method.advance_back_by) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#184)1.37.0 · #### fn nth\_back(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element from the end of the iterator. [Read more](../iter/trait.doubleendediterator#method.nth_back) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#221-225)1.27.0 · #### fn try\_rfold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, This is the reverse version of [`Iterator::try_fold()`](../iter/trait.iterator#method.try_fold "Iterator::try_fold()"): it takes elements starting from the back of the iterator. [Read more](../iter/trait.doubleendediterator#method.try_rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#292-295)1.27.0 · #### fn rfold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. [Read more](../iter/trait.doubleendediterator#method.rfold) [source](https://doc.rust-lang.org/src/core/iter/traits/double_ended.rs.html#347-350)1.27.0 · #### fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator from the back that satisfies a predicate. [Read more](../iter/trait.doubleendediterator#method.rfind) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)### impl<'a, P> Iterator for RSplit<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [ReverseSearcher](pattern/trait.reversesearcher "trait std::str::pattern::ReverseSearcher")<'a>, #### type Item = &'a str The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)#### fn next(&mut self) -> Option<&'a str> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#215)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)#### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)#### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)#### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)#### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)#### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)#### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)#### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)#### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)#### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)#### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)#### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)#### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)#### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)#### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)#### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)#### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)#### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)#### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)#### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)#### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)#### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#730-746)1.26.0 · ### impl<'a, P> FusedIterator for RSplit<'a, P>where P: [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>, <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [ReverseSearcher](pattern/trait.reversesearcher "trait std::str::pattern::ReverseSearcher")<'a>, Auto Trait Implementations -------------------------- ### impl<'a, P> RefUnwindSafe for RSplit<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, P> Send for RSplit<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Send](../marker/trait.send "trait std::marker::Send"), ### impl<'a, P> Sync for RSplit<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, P> Unpin for RSplit<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, P> UnwindSafe for RSplit<'a, P>where <P as [Pattern](pattern/trait.pattern "trait std::str::pattern::Pattern")<'a>>::[Searcher](pattern/trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::str::EscapeDefault Struct std::str::EscapeDefault ============================== ``` pub struct EscapeDefault<'a> { /* private fields */ } ``` The return type of [`str::escape_default`](../primitive.str#method.escape_default "str::escape_default"). Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1448)### impl<'a> Clone for EscapeDefault<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1448)#### fn clone(&self) -> EscapeDefault<'a> Notable traits for [EscapeDefault](struct.escapedefault "struct std::str::EscapeDefault")<'a> ``` impl<'a> Iterator for EscapeDefault<'a> type Item = char; ``` Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1448)### impl<'a> Debug for EscapeDefault<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1448)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)### impl<'a> Display for EscapeDefault<'a> [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)### impl<'a> Iterator for EscapeDefault<'a> #### type Item = char The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn next(&mut self) -> Option<char> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn try\_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> Rwhere Fold: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Acc, <[EscapeDefault](struct.escapedefault "struct std::str::EscapeDefault")<'a> as [Iterator](../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Acc>, [EscapeDefault](struct.escapedefault "struct std::str::EscapeDefault")<'a>: [Sized](../marker/trait.sized "trait std::marker::Sized"), An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)#### fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Accwhere Fold: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Acc, <[EscapeDefault](struct.escapedefault "struct std::str::EscapeDefault")<'a> as [Iterator](../iter/trait.iterator "trait std::iter::Iterator")>::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Acc, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)1.57.0 · #### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3312-3314)1.0.0 · #### fn cycle(self) -> Cycle<Self>where Self: [Clone](../clone/trait.clone "trait std::clone::Clone"), Notable traits for [Cycle](../iter/struct.cycle "struct std::iter::Cycle")<I> ``` impl<I> Iterator for Cycle<I>where     I: Clone + Iterator, type Item = <I as Iterator>::Item; ``` Repeats an iterator endlessly. [Read more](../iter/trait.iterator#method.cycle) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) [source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1499)### impl<'a> FusedIterator for EscapeDefault<'a> Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for EscapeDefault<'a> ### impl<'a> Send for EscapeDefault<'a> ### impl<'a> Sync for EscapeDefault<'a> ### impl<'a> Unpin for EscapeDefault<'a> ### impl<'a> UnwindSafe for EscapeDefault<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2500)### impl<T> ToString for Twhere T: [Display](../fmt/trait.display "trait std::fmt::Display") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2506)#### default fn to\_string(&self) -> String Converts the given value to a `String`. [Read more](../string/trait.tostring#tymethod.to_string) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Enum std::str::pattern::SearchStep Enum std::str::pattern::SearchStep ================================== ``` pub enum SearchStep { Match(usize, usize), Reject(usize, usize), Done, } ``` 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Result of calling [`Searcher::next()`](trait.searcher#tymethod.next "Searcher::next()") or [`ReverseSearcher::next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back()"). Variants -------- ### `Match([usize](../../primitive.usize), [usize](../../primitive.usize))` 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Expresses that a match of the pattern has been found at `haystack[a..b]`. ### `Reject([usize](../../primitive.usize), [usize](../../primitive.usize))` 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Expresses that `haystack[a..b]` has been rejected as a possible match of the pattern. Note that there might be more than one `Reject` between two `Match`es, there is no requirement for them to be combined into one. ### `Done` 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Expresses that every byte of the haystack has been visited, ending the iteration. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#167)### impl Clone for SearchStep [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#167)#### fn clone(&self) -> SearchStep Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#167)### impl Debug for SearchStep [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#167)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#167)### impl PartialEq<SearchStep> for SearchStep [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#167)#### fn eq(&self, other: &SearchStep) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)1.0.0 · #### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#167)### impl Copy for SearchStep [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#167)### impl Eq for SearchStep [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#167)### impl StructuralEq for SearchStep [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#167)### impl StructuralPartialEq for SearchStep Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for SearchStep ### impl Send for SearchStep ### impl Sync for SearchStep ### impl Unpin for SearchStep ### impl UnwindSafe for SearchStep Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Struct std::str::pattern::StrSearcher Struct std::str::pattern::StrSearcher ===================================== ``` pub struct StrSearcher<'a, 'b> { /* private fields */ } ``` 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Associated type for `<&str as Pattern<'a>>::Searcher`. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#983)### impl<'a, 'b> Clone for StrSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#983)#### fn clone(&self) -> StrSearcher<'a, 'b> Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#983)### impl<'a, 'b> Debug for StrSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#983)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#1125)### impl<'a, 'b> ReverseSearcher<'a> for StrSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#1127)#### fn next\_back(&mut self) -> SearchStep 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Performs the next search step starting from the back. [Read more](trait.reversesearcher#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#1173)#### fn next\_match\_back(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result. See [`next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back"). [Read more](trait.reversesearcher#method.next_match_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#312)#### fn next\_reject\_back(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") result. See [`next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back"). [Read more](trait.reversesearcher#method.next_reject_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#1035)### impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#1037)#### fn haystack(&self) -> &'a str 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Getter for the underlying string to be searched in [Read more](trait.searcher#tymethod.haystack) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#1042)#### fn next(&mut self) -> SearchStep 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Performs the next search step starting from the front. [Read more](trait.searcher#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#1094)#### fn next\_match(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result. See [`next()`](trait.searcher#tymethod.next "Searcher::next"). [Read more](trait.searcher#method.next_match) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#247)#### fn next\_reject(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") result. See [`next()`](trait.searcher#tymethod.next "Searcher::next") and [`next_match()`](trait.searcher#method.next_match "Searcher::next_match"). [Read more](trait.searcher#method.next_reject) Auto Trait Implementations -------------------------- ### impl<'a, 'b> RefUnwindSafe for StrSearcher<'a, 'b> ### impl<'a, 'b> Send for StrSearcher<'a, 'b> ### impl<'a, 'b> Sync for StrSearcher<'a, 'b> ### impl<'a, 'b> Unpin for StrSearcher<'a, 'b> ### impl<'a, 'b> UnwindSafe for StrSearcher<'a, 'b> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Trait std::str::pattern::Searcher Trait std::str::pattern::Searcher ================================= ``` pub unsafe trait Searcher<'a> { fn haystack(&self) -> &'a str; fn next(&mut self) -> SearchStep; fn next_match(&mut self) -> Option<(usize, usize)> { ... } fn next_reject(&mut self) -> Option<(usize, usize)> { ... } } ``` 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) A searcher for a string pattern. This trait provides methods for searching for non-overlapping matches of a pattern starting from the front (left) of a string. It will be implemented by associated `Searcher` types of the [`Pattern`](trait.pattern "Pattern") trait. The trait is marked unsafe because the indices returned by the [`next()`](trait.searcher#tymethod.next "Searcher::next") methods are required to lie on valid utf8 boundaries in the haystack. This enables consumers of this trait to slice the haystack without additional runtime checks. Required Methods ---------------- [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#199)#### fn haystack(&self) -> &'a str 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Getter for the underlying string to be searched in Will always return the same [`&str`](../../primitive.str "str"). [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#222)#### fn next(&mut self) -> SearchStep 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Performs the next search step starting from the front. * Returns [`Match(a, b)`](enum.searchstep#variant.Match "SearchStep::Match") if `haystack[a..b]` matches the pattern. * Returns [`Reject(a, b)`](enum.searchstep#variant.Reject "SearchStep::Reject") if `haystack[a..b]` can not match the pattern, even partially. * Returns [`Done`](enum.searchstep#variant.Done "SearchStep::Done") if every byte of the haystack has been visited. The stream of [`Match`](enum.searchstep#variant.Match "SearchStep::Match") and [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") values up to a [`Done`](enum.searchstep#variant.Done "SearchStep::Done") will contain index ranges that are adjacent, non-overlapping, covering the whole haystack, and laying on utf8 boundaries. A [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result needs to contain the whole matched pattern, however [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") results may be split up into arbitrary many adjacent fragments. Both ranges may have zero length. As an example, the pattern `"aaa"` and the haystack `"cbaaaaab"` might produce the stream `[Reject(0, 1), Reject(1, 2), Match(2, 5), Reject(5, 8)]` Provided Methods ---------------- [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#231)#### fn next\_match(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result. See [`next()`](trait.searcher#tymethod.next "Searcher::next"). Unlike [`next()`](trait.searcher#tymethod.next "Searcher::next"), there is no guarantee that the returned ranges of this and [`next_reject`](trait.searcher#method.next_reject "Searcher::next_reject") will overlap. This will return `(start_match, end_match)`, where start\_match is the index of where the match begins, and end\_match is the index after the end of the match. [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#247)#### fn next\_reject(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") result. See [`next()`](trait.searcher#tymethod.next "Searcher::next") and [`next_match()`](trait.searcher#method.next_match "Searcher::next_match"). Unlike [`next()`](trait.searcher#tymethod.next "Searcher::next"), there is no guarantee that the returned ranges of this and [`next_match`](trait.searcher#method.next_match "Searcher::next_match") will overlap. Implementors ------------ [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#377)### impl<'a> Searcher<'a> for CharSearcher<'a> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#838)### impl<'a, 'b> Searcher<'a> for CharSliceSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#1035)### impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#820)### impl<'a, 'b, const N: usize> Searcher<'a> for CharArrayRefSearcher<'a, 'b, N> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#881)### impl<'a, F> Searcher<'a> for CharPredicateSearcher<'a, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([char](../../primitive.char)) -> [bool](../../primitive.bool), [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#800)### impl<'a, const N: usize> Searcher<'a> for CharArraySearcher<'a, N>
programming_docs
rust Module std::str::pattern Module std::str::pattern ======================== 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) The string Pattern API. The Pattern API provides a generic mechanism for using different pattern types when searching through a string. For more details, see the traits [`Pattern`](trait.pattern "Pattern"), [`Searcher`](trait.searcher "Searcher"), [`ReverseSearcher`](trait.reversesearcher "ReverseSearcher"), and [`DoubleEndedSearcher`](trait.doubleendedsearcher "DoubleEndedSearcher"). Although this API is unstable, it is exposed via stable APIs on the [`str`](../../primitive.str "str") type. Examples -------- [`Pattern`](trait.pattern "Pattern") is [implemented](trait.pattern#implementors) in the stable API for [`&str`](../../primitive.str "str"), [`char`](../../primitive.char "char"), slices of [`char`](../../primitive.char "char"), and functions and closures implementing `FnMut(char) -> bool`. ``` let s = "Can you find a needle in a haystack?"; // &str pattern assert_eq!(s.find("you"), Some(4)); // char pattern assert_eq!(s.find('n'), Some(2)); // array of chars pattern assert_eq!(s.find(&['a', 'e', 'i', 'o', 'u']), Some(1)); // slice of chars pattern assert_eq!(s.find(&['a', 'e', 'i', 'o', 'u'][..]), Some(1)); // closure pattern assert_eq!(s.find(|c: char| c.is_ascii_punctuation()), Some(35)); ``` Structs ------- [CharArrayRefSearcher](struct.chararrayrefsearcher "std::str::pattern::CharArrayRefSearcher struct")Experimental Associated type for `<&[char; N] as Pattern<'a>>::Searcher`. [CharArraySearcher](struct.chararraysearcher "std::str::pattern::CharArraySearcher struct")Experimental Associated type for `<[char; N] as Pattern<'a>>::Searcher`. [CharPredicateSearcher](struct.charpredicatesearcher "std::str::pattern::CharPredicateSearcher struct")Experimental Associated type for `<F as Pattern<'a>>::Searcher`. [CharSearcher](struct.charsearcher "std::str::pattern::CharSearcher struct")Experimental Associated type for `<char as Pattern<'a>>::Searcher`. [CharSliceSearcher](struct.charslicesearcher "std::str::pattern::CharSliceSearcher struct")Experimental Associated type for `<&[char] as Pattern<'a>>::Searcher`. [StrSearcher](struct.strsearcher "std::str::pattern::StrSearcher struct")Experimental Associated type for `<&str as Pattern<'a>>::Searcher`. Enums ----- [SearchStep](enum.searchstep "std::str::pattern::SearchStep enum")Experimental Result of calling [`Searcher::next()`](trait.searcher#tymethod.next "Searcher::next()") or [`ReverseSearcher::next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back()"). Traits ------ [DoubleEndedSearcher](trait.doubleendedsearcher "std::str::pattern::DoubleEndedSearcher trait")Experimental A marker trait to express that a [`ReverseSearcher`](trait.reversesearcher "ReverseSearcher") can be used for a [`DoubleEndedIterator`](../../iter/trait.doubleendediterator "DoubleEndedIterator") implementation. [Pattern](trait.pattern "std::str::pattern::Pattern trait")Experimental A string pattern. [ReverseSearcher](trait.reversesearcher "std::str::pattern::ReverseSearcher trait")Experimental A reverse searcher for a string pattern. [Searcher](trait.searcher "std::str::pattern::Searcher trait")Experimental A searcher for a string pattern. rust Struct std::str::pattern::CharSliceSearcher Struct std::str::pattern::CharSliceSearcher =========================================== ``` pub struct CharSliceSearcher<'a, 'b>(_); ``` 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Associated type for `<&[char] as Pattern<'a>>::Searcher`. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#835)### impl<'a, 'b> Clone for CharSliceSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#835)#### fn clone(&self) -> CharSliceSearcher<'a, 'b> Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#835)### impl<'a, 'b> Debug for CharSliceSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#835)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#842)### impl<'a, 'b> ReverseSearcher<'a> for CharSliceSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#843)#### fn next\_back(&mut self) -> SearchStep 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Performs the next search step starting from the back. [Read more](trait.reversesearcher#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#843)#### fn next\_match\_back(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result. See [`next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back"). [Read more](trait.reversesearcher#method.next_match_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#843)#### fn next\_reject\_back(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") result. See [`next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back"). [Read more](trait.reversesearcher#method.next_reject_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#838)### impl<'a, 'b> Searcher<'a> for CharSliceSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#839)#### fn haystack(&self) -> &'a str 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Getter for the underlying string to be searched in [Read more](trait.searcher#tymethod.haystack) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#839)#### fn next(&mut self) -> SearchStep 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Performs the next search step starting from the front. [Read more](trait.searcher#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#839)#### fn next\_match(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result. See [`next()`](trait.searcher#tymethod.next "Searcher::next"). [Read more](trait.searcher#method.next_match) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#839)#### fn next\_reject(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") result. See [`next()`](trait.searcher#tymethod.next "Searcher::next") and [`next_match()`](trait.searcher#method.next_match "Searcher::next_match"). [Read more](trait.searcher#method.next_reject) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#846)### impl<'a, 'b> DoubleEndedSearcher<'a> for CharSliceSearcher<'a, 'b> Auto Trait Implementations -------------------------- ### impl<'a, 'b> RefUnwindSafe for CharSliceSearcher<'a, 'b> ### impl<'a, 'b> Send for CharSliceSearcher<'a, 'b> ### impl<'a, 'b> Sync for CharSliceSearcher<'a, 'b> ### impl<'a, 'b> Unpin for CharSliceSearcher<'a, 'b> ### impl<'a, 'b> UnwindSafe for CharSliceSearcher<'a, 'b> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Trait std::str::pattern::Pattern Trait std::str::pattern::Pattern ================================ ``` pub trait Pattern<'a> { type Searcher: Searcher<'a>; fn into_searcher(self, haystack: &'a str) -> Self::Searcher; fn is_contained_in(self, haystack: &'a str) -> bool { ... } fn is_prefix_of(self, haystack: &'a str) -> bool { ... } fn is_suffix_of(self, haystack: &'a str) -> bool    where        Self::Searcher: ReverseSearcher<'a>, { ... } fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> { ... } fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str>    where        Self::Searcher: ReverseSearcher<'a>, { ... } } ``` 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) A string pattern. A `Pattern<'a>` expresses that the implementing type can be used as a string pattern for searching in a [`&'a str`](../../primitive.str "str"). For example, both `'a'` and `"aa"` are patterns that would match at index `1` in the string `"baaaab"`. The trait itself acts as a builder for an associated [`Searcher`](trait.searcher "Searcher") type, which does the actual work of finding occurrences of the pattern in a string. Depending on the type of the pattern, the behaviour of methods like [`str::find`](../../primitive.str#method.find "str::find") and [`str::contains`](../../primitive.str#method.contains "str::contains") can change. The table below describes some of those behaviours. | Pattern type | Match condition | | --- | --- | | `&str` | is substring | | `char` | is contained in string | | `&[char]` | any char in slice is contained in string | | `F: FnMut(char) -> bool` | `F` returns `true` for a char in string | | `&&str` | is substring | | `&String` | is substring | Examples -------- ``` // &str assert_eq!("abaaa".find("ba"), Some(1)); assert_eq!("abaaa".find("bac"), None); // char assert_eq!("abaaa".find('a'), Some(0)); assert_eq!("abaaa".find('b'), Some(1)); assert_eq!("abaaa".find('c'), None); // &[char; N] assert_eq!("ab".find(&['b', 'a']), Some(0)); assert_eq!("abaaa".find(&['a', 'z']), Some(0)); assert_eq!("abaaa".find(&['c', 'd']), None); // &[char] assert_eq!("ab".find(&['b', 'a'][..]), Some(0)); assert_eq!("abaaa".find(&['a', 'z'][..]), Some(0)); assert_eq!("abaaa".find(&['c', 'd'][..]), None); // FnMut(char) -> bool assert_eq!("abcdef_z".find(|ch| ch > 'd' && ch < 'y'), Some(4)); assert_eq!("abcddd_z".find(|ch| ch > 'd' && ch < 'y'), None); ``` Required Associated Types ------------------------- [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#100)#### type Searcher: Searcher<'a> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Associated searcher for this pattern Required Methods ---------------- [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#104)#### fn into\_searcher(self, haystack: &'a str) -> Self::Searcher 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Constructs the associated searcher from `self` and the `haystack` to search in. Provided Methods ---------------- [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#108)#### fn is\_contained\_in(self, haystack: &'a str) -> bool 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Checks whether the pattern matches anywhere in the haystack [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#114)#### fn is\_prefix\_of(self, haystack: &'a str) -> bool 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Checks whether the pattern matches at the front of the haystack [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#120-122)#### fn is\_suffix\_of(self, haystack: &'a str) -> boolwhere Self::[Searcher](trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [ReverseSearcher](trait.reversesearcher "trait std::str::pattern::ReverseSearcher")<'a>, 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Checks whether the pattern matches at the back of the haystack [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#129)#### fn strip\_prefix\_of(self, haystack: &'a str) -> Option<&'a str> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Removes the pattern from the front of haystack, if it matches. [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#145-147)#### fn strip\_suffix\_of(self, haystack: &'a str) -> Option<&'a str>where Self::[Searcher](trait.pattern#associatedtype.Searcher "type std::str::pattern::Pattern::Searcher"): [ReverseSearcher](trait.reversesearcher "trait std::str::pattern::ReverseSearcher")<'a>, 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Removes the pattern from the back of haystack, if it matches. Implementors ------------ [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#538)### impl<'a> Pattern<'a> for char Searches for chars that are equal to a given [`char`](../../primitive.char "char"). #### Examples ``` assert_eq!("Hello world".find('o'), Some(4)); ``` #### type Searcher = CharSearcher<'a> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#935)### impl<'a, 'b> Pattern<'a> for &'b str Non-allocating substring search. Will handle the pattern `""` as returning empty matches at each character boundary. #### Examples ``` assert_eq!("Hello world".find("world"), Some(6)); ``` #### type Searcher = StrSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2151)### impl<'a, 'b> Pattern<'a> for &'b String A convenience impl that delegates to the impl for `&str`. #### Examples ``` assert_eq!(String::from("Hello world").find("world"), Some(6)); ``` #### type Searcher = <&'b str as Pattern<'a>>::Searcher [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#856)### impl<'a, 'b> Pattern<'a> for &'b [char] Searches for chars that are equal to any of the [`char`](../../primitive.char "char")s in the slice. #### Examples ``` assert_eq!("Hello world".find(&['l', 'l'] as &[_]), Some(2)); assert_eq!("Hello world".find(&['l', 'l'][..]), Some(2)); ``` #### type Searcher = CharSliceSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#917)### impl<'a, 'b, 'c> Pattern<'a> for &'c &'b str Delegates to the `&str` impl. #### type Searcher = StrSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#816)### impl<'a, 'b, const N: usize> Pattern<'a> for &'b [char; N] Searches for chars that are equal to any of the [`char`](../../primitive.char "char")s in the array. #### Examples ``` assert_eq!("Hello world".find(&['l', 'l']), Some(2)); assert_eq!("Hello world".find(&['l', 'l']), Some(2)); ``` #### type Searcher = CharArrayRefSearcher<'a, 'b, N> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#905)### impl<'a, F> Pattern<'a> for Fwhere F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([char](../../primitive.char)) -> [bool](../../primitive.bool), Searches for [`char`](../../primitive.char "char")s that match the given predicate. #### Examples ``` assert_eq!("Hello world".find(char::is_uppercase), Some(0)); assert_eq!("Hello world".find(|c| "aeiou".contains(c)), Some(1)); ``` #### type Searcher = CharPredicateSearcher<'a, F> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#796)### impl<'a, const N: usize> Pattern<'a> for [char; N] Searches for chars that are equal to any of the [`char`](../../primitive.char "char")s in the array. #### Examples ``` assert_eq!("Hello world".find(['l', 'l']), Some(2)); assert_eq!("Hello world".find(['l', 'l']), Some(2)); ``` #### type Searcher = CharArraySearcher<'a, N>
programming_docs
rust Struct std::str::pattern::CharArrayRefSearcher Struct std::str::pattern::CharArrayRefSearcher ============================================== ``` pub struct CharArrayRefSearcher<'a, 'b, const N: usize>(_); ``` 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Associated type for `<&[char; N] as Pattern<'a>>::Searcher`. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#783)### impl<'a, 'b, const N: usize> Clone for CharArrayRefSearcher<'a, 'b, N> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#783)#### fn clone(&self) -> CharArrayRefSearcher<'a, 'b, N> Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#783)### impl<'a, 'b, const N: usize> Debug for CharArrayRefSearcher<'a, 'b, N> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#783)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#824)### impl<'a, 'b, const N: usize> ReverseSearcher<'a> for CharArrayRefSearcher<'a, 'b, N> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#825)#### fn next\_back(&mut self) -> SearchStep 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Performs the next search step starting from the back. [Read more](trait.reversesearcher#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#825)#### fn next\_match\_back(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result. See [`next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back"). [Read more](trait.reversesearcher#method.next_match_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#825)#### fn next\_reject\_back(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") result. See [`next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back"). [Read more](trait.reversesearcher#method.next_reject_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#820)### impl<'a, 'b, const N: usize> Searcher<'a> for CharArrayRefSearcher<'a, 'b, N> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#821)#### fn haystack(&self) -> &'a str 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Getter for the underlying string to be searched in [Read more](trait.searcher#tymethod.haystack) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#821)#### fn next(&mut self) -> SearchStep 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Performs the next search step starting from the front. [Read more](trait.searcher#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#821)#### fn next\_match(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result. See [`next()`](trait.searcher#tymethod.next "Searcher::next"). [Read more](trait.searcher#method.next_match) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#821)#### fn next\_reject(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") result. See [`next()`](trait.searcher#tymethod.next "Searcher::next") and [`next_match()`](trait.searcher#method.next_match "Searcher::next_match"). [Read more](trait.searcher#method.next_reject) Auto Trait Implementations -------------------------- ### impl<'a, 'b, const N: usize> RefUnwindSafe for CharArrayRefSearcher<'a, 'b, N> ### impl<'a, 'b, const N: usize> Send for CharArrayRefSearcher<'a, 'b, N> ### impl<'a, 'b, const N: usize> Sync for CharArrayRefSearcher<'a, 'b, N> ### impl<'a, 'b, const N: usize> Unpin for CharArrayRefSearcher<'a, 'b, N> ### impl<'a, 'b, const N: usize> UnwindSafe for CharArrayRefSearcher<'a, 'b, N> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Struct std::str::pattern::CharPredicateSearcher Struct std::str::pattern::CharPredicateSearcher =============================================== ``` pub struct CharPredicateSearcher<'a, F>(_)where    F: FnMut(char) -> bool; ``` 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Associated type for `<F as Pattern<'a>>::Searcher`. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#865)### impl<'a, F> Clone for CharPredicateSearcher<'a, F>where F: [Clone](../../clone/trait.clone "trait std::clone::Clone") + [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([char](../../primitive.char)) -> [bool](../../primitive.bool), [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#865)#### fn clone(&self) -> CharPredicateSearcher<'a, F> Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#870)### impl<F> Debug for CharPredicateSearcher<'\_, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([char](../../primitive.char)) -> [bool](../../primitive.bool), [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#874)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#888)### impl<'a, F> ReverseSearcher<'a> for CharPredicateSearcher<'a, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([char](../../primitive.char)) -> [bool](../../primitive.bool), [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#892)#### fn next\_back(&mut self) -> SearchStep 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Performs the next search step starting from the back. [Read more](trait.reversesearcher#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#892)#### fn next\_match\_back(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result. See [`next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back"). [Read more](trait.reversesearcher#method.next_match_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#892)#### fn next\_reject\_back(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") result. See [`next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back"). [Read more](trait.reversesearcher#method.next_reject_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#881)### impl<'a, F> Searcher<'a> for CharPredicateSearcher<'a, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([char](../../primitive.char)) -> [bool](../../primitive.bool), [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#885)#### fn haystack(&self) -> &'a str 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Getter for the underlying string to be searched in [Read more](trait.searcher#tymethod.haystack) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#885)#### fn next(&mut self) -> SearchStep 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Performs the next search step starting from the front. [Read more](trait.searcher#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#885)#### fn next\_match(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result. See [`next()`](trait.searcher#tymethod.next "Searcher::next"). [Read more](trait.searcher#method.next_match) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#885)#### fn next\_reject(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") result. See [`next()`](trait.searcher#tymethod.next "Searcher::next") and [`next_match()`](trait.searcher#method.next_match "Searcher::next_match"). [Read more](trait.searcher#method.next_reject) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#895)### impl<'a, F> DoubleEndedSearcher<'a> for CharPredicateSearcher<'a, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([char](../../primitive.char)) -> [bool](../../primitive.bool), Auto Trait Implementations -------------------------- ### impl<'a, F> RefUnwindSafe for CharPredicateSearcher<'a, F>where F: [RefUnwindSafe](../../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<'a, F> Send for CharPredicateSearcher<'a, F>where F: [Send](../../marker/trait.send "trait std::marker::Send"), ### impl<'a, F> Sync for CharPredicateSearcher<'a, F>where F: [Sync](../../marker/trait.sync "trait std::marker::Sync"), ### impl<'a, F> Unpin for CharPredicateSearcher<'a, F>where F: [Unpin](../../marker/trait.unpin "trait std::marker::Unpin"), ### impl<'a, F> UnwindSafe for CharPredicateSearcher<'a, F>where F: [UnwindSafe](../../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Trait std::str::pattern::ReverseSearcher Trait std::str::pattern::ReverseSearcher ======================================== ``` pub unsafe trait ReverseSearcher<'a>: Searcher<'a> { fn next_back(&mut self) -> SearchStep; fn next_match_back(&mut self) -> Option<(usize, usize)> { ... } fn next_reject_back(&mut self) -> Option<(usize, usize)> { ... } } ``` 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) A reverse searcher for a string pattern. This trait provides methods for searching for non-overlapping matches of a pattern starting from the back (right) of a string. It will be implemented by associated [`Searcher`](trait.searcher "Searcher") types of the [`Pattern`](trait.pattern "Pattern") trait if the pattern supports searching for it from the back. The index ranges returned by this trait are not required to exactly match those of the forward search in reverse. For the reason why this trait is marked unsafe, see them parent trait [`Searcher`](trait.searcher "Searcher"). Required Methods ---------------- [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#294)#### fn next\_back(&mut self) -> SearchStep 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Performs the next search step starting from the back. * Returns [`Match(a, b)`](enum.searchstep#variant.Match "SearchStep::Match") if `haystack[a..b]` matches the pattern. * Returns [`Reject(a, b)`](enum.searchstep#variant.Reject "SearchStep::Reject") if `haystack[a..b]` can not match the pattern, even partially. * Returns [`Done`](enum.searchstep#variant.Done "SearchStep::Done") if every byte of the haystack has been visited The stream of [`Match`](enum.searchstep#variant.Match "SearchStep::Match") and [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") values up to a [`Done`](enum.searchstep#variant.Done "SearchStep::Done") will contain index ranges that are adjacent, non-overlapping, covering the whole haystack, and laying on utf8 boundaries. A [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result needs to contain the whole matched pattern, however [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") results may be split up into arbitrary many adjacent fragments. Both ranges may have zero length. As an example, the pattern `"aaa"` and the haystack `"cbaaaaab"` might produce the stream `[Reject(7, 8), Match(4, 7), Reject(1, 4), Reject(0, 1)]`. Provided Methods ---------------- [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#299)#### fn next\_match\_back(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result. See [`next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back"). [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#312)#### fn next\_reject\_back(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") result. See [`next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back"). Implementors ------------ [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#455)### impl<'a> ReverseSearcher<'a> for CharSearcher<'a> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#842)### impl<'a, 'b> ReverseSearcher<'a> for CharSliceSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#1125)### impl<'a, 'b> ReverseSearcher<'a> for StrSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#824)### impl<'a, 'b, const N: usize> ReverseSearcher<'a> for CharArrayRefSearcher<'a, 'b, N> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#888)### impl<'a, F> ReverseSearcher<'a> for CharPredicateSearcher<'a, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([char](../../primitive.char)) -> [bool](../../primitive.bool), [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#804)### impl<'a, const N: usize> ReverseSearcher<'a> for CharArraySearcher<'a, N>
programming_docs
rust Struct std::str::pattern::CharArraySearcher Struct std::str::pattern::CharArraySearcher =========================================== ``` pub struct CharArraySearcher<'a, const N: usize>(_); ``` 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Associated type for `<[char; N] as Pattern<'a>>::Searcher`. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#777)### impl<'a, const N: usize> Clone for CharArraySearcher<'a, N> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#777)#### fn clone(&self) -> CharArraySearcher<'a, N> Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#777)### impl<'a, const N: usize> Debug for CharArraySearcher<'a, N> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#777)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#804)### impl<'a, const N: usize> ReverseSearcher<'a> for CharArraySearcher<'a, N> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#805)#### fn next\_back(&mut self) -> SearchStep 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Performs the next search step starting from the back. [Read more](trait.reversesearcher#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#805)#### fn next\_match\_back(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result. See [`next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back"). [Read more](trait.reversesearcher#method.next_match_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#805)#### fn next\_reject\_back(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") result. See [`next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back"). [Read more](trait.reversesearcher#method.next_reject_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#800)### impl<'a, const N: usize> Searcher<'a> for CharArraySearcher<'a, N> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#801)#### fn haystack(&self) -> &'a str 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Getter for the underlying string to be searched in [Read more](trait.searcher#tymethod.haystack) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#801)#### fn next(&mut self) -> SearchStep 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Performs the next search step starting from the front. [Read more](trait.searcher#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#801)#### fn next\_match(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result. See [`next()`](trait.searcher#tymethod.next "Searcher::next"). [Read more](trait.searcher#method.next_match) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#801)#### fn next\_reject(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") result. See [`next()`](trait.searcher#tymethod.next "Searcher::next") and [`next_match()`](trait.searcher#method.next_match "Searcher::next_match"). [Read more](trait.searcher#method.next_reject) Auto Trait Implementations -------------------------- ### impl<'a, const N: usize> RefUnwindSafe for CharArraySearcher<'a, N> ### impl<'a, const N: usize> Send for CharArraySearcher<'a, N> ### impl<'a, const N: usize> Sync for CharArraySearcher<'a, N> ### impl<'a, const N: usize> Unpin for CharArraySearcher<'a, N> ### impl<'a, const N: usize> UnwindSafe for CharArraySearcher<'a, N> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Trait std::str::pattern::DoubleEndedSearcher Trait std::str::pattern::DoubleEndedSearcher ============================================ ``` pub trait DoubleEndedSearcher<'a>: ReverseSearcher<'a> { } ``` 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) A marker trait to express that a [`ReverseSearcher`](trait.reversesearcher "ReverseSearcher") can be used for a [`DoubleEndedIterator`](../../iter/trait.doubleendediterator "DoubleEndedIterator") implementation. For this, the impl of [`Searcher`](trait.searcher "Searcher") and [`ReverseSearcher`](trait.reversesearcher "ReverseSearcher") need to follow these conditions: * All results of `next()` need to be identical to the results of `next_back()` in reverse order. * `next()` and `next_back()` need to behave as the two ends of a range of values, that is they can not “walk past each other”. Examples -------- `char::Searcher` is a `DoubleEndedSearcher` because searching for a [`char`](../../primitive.char "char") only requires looking at one at a time, which behaves the same from both ends. `(&str)::Searcher` is not a `DoubleEndedSearcher` because the pattern `"aa"` in the haystack `"aaa"` matches as either `"[aa]a"` or `"a[aa]"`, depending from which side it is searched. Implementors ------------ [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#529)### impl<'a> DoubleEndedSearcher<'a> for CharSearcher<'a> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#846)### impl<'a, 'b> DoubleEndedSearcher<'a> for CharSliceSearcher<'a, 'b> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#895)### impl<'a, F> DoubleEndedSearcher<'a> for CharPredicateSearcher<'a, F>where F: [FnMut](../../ops/trait.fnmut "trait std::ops::FnMut")([char](../../primitive.char)) -> [bool](../../primitive.bool), rust Struct std::str::pattern::CharSearcher Struct std::str::pattern::CharSearcher ====================================== ``` pub struct CharSearcher<'a> { /* private fields */ } ``` 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Associated type for `<char as Pattern<'a>>::Searcher`. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#351)### impl<'a> Clone for CharSearcher<'a> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#351)#### fn clone(&self) -> CharSearcher<'a> Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#351)### impl<'a> Debug for CharSearcher<'a> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#351)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#455)### impl<'a> ReverseSearcher<'a> for CharSearcher<'a> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#457)#### fn next\_back(&mut self) -> SearchStep 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Performs the next search step starting from the back. [Read more](trait.reversesearcher#tymethod.next_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#477)#### fn next\_match\_back(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result. See [`next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back"). [Read more](trait.reversesearcher#method.next_match_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#312)#### fn next\_reject\_back(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") result. See [`next_back()`](trait.reversesearcher#tymethod.next_back "ReverseSearcher::next_back"). [Read more](trait.reversesearcher#method.next_reject_back) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#377)### impl<'a> Searcher<'a> for CharSearcher<'a> [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#379)#### fn haystack(&self) -> &'a str 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Getter for the underlying string to be searched in [Read more](trait.searcher#tymethod.haystack) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#383)#### fn next(&mut self) -> SearchStep 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Performs the next search step starting from the front. [Read more](trait.searcher#tymethod.next) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#410)#### fn next\_match(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Match`](enum.searchstep#variant.Match "SearchStep::Match") result. See [`next()`](trait.searcher#tymethod.next "Searcher::next"). [Read more](trait.searcher#method.next_match) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#247)#### fn next\_reject(&mut self) -> Option<(usize, usize)> 🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721)) Finds the next [`Reject`](enum.searchstep#variant.Reject "SearchStep::Reject") result. See [`next()`](trait.searcher#tymethod.next "Searcher::next") and [`next_match()`](trait.searcher#method.next_match "Searcher::next_match"). [Read more](trait.searcher#method.next_reject) [source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#529)### impl<'a> DoubleEndedSearcher<'a> for CharSearcher<'a> Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for CharSearcher<'a> ### impl<'a> Send for CharSearcher<'a> ### impl<'a> Sync for CharSearcher<'a> ### impl<'a> Unpin for CharSearcher<'a> ### impl<'a> UnwindSafe for CharSearcher<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Function std::mem::align_of_val_raw Function std::mem::align\_of\_val\_raw ====================================== ``` pub unsafe fn align_of_val_raw<T>(val: *const T) -> usizewhere    T: ?Sized, ``` 🔬This is a nightly-only experimental API. (`layout_for_ptr` [#69835](https://github.com/rust-lang/rust/issues/69835)) Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface)-required minimum alignment of the type of the value that `val` points to in bytes. Every reference to a value of the type `T` must be a multiple of this number. Safety ------ This function is only safe to call if the following conditions hold: * If `T` is `Sized`, this function is always safe to call. * If the unsized tail of `T` is: + a [slice](../primitive.slice "slice"), then the length of the slice tail must be an initialized integer, and the size of the *entire value* (dynamic tail length + statically sized prefix) must fit in `isize`. + a [trait object](../../book/ch17-02-trait-objects), then the vtable part of the pointer must point to a valid vtable acquired by an unsizing coercion, and the size of the *entire value* (dynamic tail length + statically sized prefix) must fit in `isize`. + an (unstable) [extern type](https://doc.rust-lang.org/unstable-book/language-features/extern-types.html), then this function is always safe to call, but may panic or otherwise return the wrong value, as the extern type’s layout is not known. This is the same behavior as [`align_of_val`](fn.align_of_val "align_of_val") on a reference to a type with an extern type tail. + otherwise, it is conservatively not allowed to call this function. Examples -------- ``` #![feature(layout_for_ptr)] use std::mem; assert_eq!(4, unsafe { mem::align_of_val_raw(&5i32) }); ```
programming_docs
rust Function std::mem::size_of_val Function std::mem::size\_of\_val ================================ ``` pub fn size_of_val<T>(val: &T) -> usizewhere    T: ?Sized, ``` Returns the size of the pointed-to value in bytes. This is usually the same as `size_of::<T>()`. However, when `T` *has* no statically-known size, e.g., a slice [`[T]`](../primitive.slice "slice") or a [trait object](../../book/ch17-02-trait-objects), then `size_of_val` can be used to get the dynamically-known size. Examples -------- ``` use std::mem; assert_eq!(4, mem::size_of_val(&5i32)); let x: [u8; 13] = [0; 13]; let y: &[u8] = &x; assert_eq!(13, mem::size_of_val(y)); ``` rust Function std::mem::align_of_val Function std::mem::align\_of\_val ================================= ``` pub fn align_of_val<T>(val: &T) -> usizewhere    T: ?Sized, ``` Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface)-required minimum alignment of the type of the value that `val` points to in bytes. Every reference to a value of the type `T` must be a multiple of this number. Examples -------- ``` use std::mem; assert_eq!(4, mem::align_of_val(&5i32)); ``` rust Module std::mem Module std::mem =============== Basic functions for dealing with memory. This module contains functions for querying the size and alignment of types, initializing and manipulating memory. Structs ------- [Assume](struct.assume "std::mem::Assume struct")Experimental What transmutation safety conditions shall the compiler assume that *you* are checking? [Discriminant](struct.discriminant "std::mem::Discriminant struct") Opaque type representing the discriminant of an enum. [ManuallyDrop](struct.manuallydrop "std::mem::ManuallyDrop struct") A wrapper to inhibit compiler from automatically calling `T`’s destructor. This wrapper is 0-cost. Traits ------ [BikeshedIntrinsicFrom](trait.bikeshedintrinsicfrom "std::mem::BikeshedIntrinsicFrom trait")Experimental Are values of a type transmutable into values of another type? Functions --------- [align\_of\_val\_raw](fn.align_of_val_raw "std::mem::align_of_val_raw fn")[⚠](# "unsafe function")Experimental Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface)-required minimum alignment of the type of the value that `val` points to in bytes. [copy](fn.copy "std::mem::copy fn")Experimental Bitwise-copies a value. [forget\_unsized](fn.forget_unsized "std::mem::forget_unsized fn")Experimental Like [`forget`](fn.forget "forget"), but also accepts unsized values. [size\_of\_val\_raw](fn.size_of_val_raw "std::mem::size_of_val_raw fn")[⚠](# "unsafe function")Experimental Returns the size of the pointed-to value in bytes. [variant\_count](fn.variant_count "std::mem::variant_count fn")Experimental Returns the number of variants in the enum type `T`. [align\_of](fn.align_of "std::mem::align_of fn") Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface)-required minimum alignment of a type in bytes. [align\_of\_val](fn.align_of_val "std::mem::align_of_val fn") Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface)-required minimum alignment of the type of the value that `val` points to in bytes. [discriminant](fn.discriminant "std::mem::discriminant fn") Returns a value uniquely identifying the enum variant in `v`. [drop](fn.drop "std::mem::drop fn") Disposes of a value. [forget](fn.forget "std::mem::forget fn") Takes ownership and “forgets” about the value **without running its destructor**. [min\_align\_of](fn.min_align_of "std::mem::min_align_of fn")Deprecated Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface)-required minimum alignment of a type in bytes. [min\_align\_of\_val](fn.min_align_of_val "std::mem::min_align_of_val fn")Deprecated Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface)-required minimum alignment of the type of the value that `val` points to in bytes. [needs\_drop](fn.needs_drop "std::mem::needs_drop fn") Returns `true` if dropping values of type `T` matters. [replace](fn.replace "std::mem::replace fn") Moves `src` into the referenced `dest`, returning the previous `dest` value. [size\_of](fn.size_of "std::mem::size_of fn") Returns the size of a type in bytes. [size\_of\_val](fn.size_of_val "std::mem::size_of_val fn") Returns the size of the pointed-to value in bytes. [swap](fn.swap "std::mem::swap fn") Swaps the values at two mutable locations, without deinitializing either one. [take](fn.take "std::mem::take fn") Replaces `dest` with the default value of `T`, returning the previous `dest` value. [transmute](fn.transmute "std::mem::transmute fn")[⚠](# "unsafe function") Reinterprets the bits of a value of one type as another type. [transmute\_copy](fn.transmute_copy "std::mem::transmute_copy fn")[⚠](# "unsafe function") Interprets `src` as having type `&U`, and then reads `src` without moving the contained value. [uninitialized](fn.uninitialized "std::mem::uninitialized fn")[⚠](# "unsafe function")Deprecated Bypasses Rust’s normal memory-initialization checks by pretending to produce a value of type `T`, while doing nothing at all. [zeroed](fn.zeroed "std::mem::zeroed fn")[⚠](# "unsafe function") Returns the value of type `T` represented by the all-zero byte-pattern. Unions ------ [MaybeUninit](union.maybeuninit "std::mem::MaybeUninit union") A wrapper type to construct uninitialized instances of `T`. rust Function std::mem::uninitialized Function std::mem::uninitialized ================================ ``` pub unsafe fn uninitialized<T>() -> T ``` 👎Deprecated since 1.39.0: use `mem::MaybeUninit` instead Bypasses Rust’s normal memory-initialization checks by pretending to produce a value of type `T`, while doing nothing at all. **This function is deprecated.** Use [`MaybeUninit<T>`](union.maybeuninit "MaybeUninit<T>") instead. It also might be slower than using `MaybeUninit<T>` due to mitigations that were put in place to limit the potential harm caused by incorrect use of this function in legacy code. The reason for deprecation is that the function basically cannot be used correctly: it has the same effect as [`MaybeUninit::uninit().assume_init()`](union.maybeuninit#method.uninit). As the [`assume_init` documentation](union.maybeuninit#method.assume_init) explains, [the Rust compiler assumes](union.maybeuninit#initialization-invariant) that values are properly initialized. Truly uninitialized memory like what gets returned here is special in that the compiler knows that it does not have a fixed value. This makes it undefined behavior to have uninitialized data in a variable even if that variable has an integer type. Therefore, it is immediate undefined behavior to call this function on nearly all types, including integer types and arrays of integer types, and even if the result is unused. rust Function std::mem::transmute Function std::mem::transmute ============================ ``` pub const unsafe extern "rust-intrinsic" fn transmute<T, U>(e: T) -> U ``` Reinterprets the bits of a value of one type as another type. Both types must have the same size. Compilation will fail if this is not guaranteed. `transmute` is semantically equivalent to a bitwise move of one type into another. It copies the bits from the source value into the destination value, then forgets the original. Note that source and destination are passed by-value, which means if `T` or `U` contain padding, that padding is *not* guaranteed to be preserved by `transmute`. Both the argument and the result must be [valid](https://doc.rust-lang.org/nomicon/what-unsafe-does.html) at their given type. Violating this condition leads to [undefined behavior](../../reference/behavior-considered-undefined). The compiler will generate code *assuming that you, the programmer, ensure that there will never be undefined behavior*. It is therefore your responsibility to guarantee that every value passed to `transmute` is valid at both types `T` and `U`. Failing to uphold this condition may lead to unexpected and unstable compilation results. This makes `transmute` **incredibly unsafe**. `transmute` should be the absolute last resort. Transmuting pointers to integers in a `const` context is [undefined behavior](../../reference/behavior-considered-undefined). Any attempt to use the resulting value for integer operations will abort const-evaluation. (And even outside `const`, such transmutation is touching on many unspecified aspects of the Rust memory model and should be avoided. See below for alternatives.) Because `transmute` is a by-value operation, alignment of the *transmuted values themselves* is not a concern. As with any other function, the compiler already ensures both `T` and `U` are properly aligned. However, when transmuting values that *point elsewhere* (such as pointers, references, boxes…), the caller has to ensure proper alignment of the pointed-to values. The [nomicon](https://doc.rust-lang.org/nomicon/transmutes.html) has additional documentation. Examples -------- There are a few things that `transmute` is really useful for. Turning a pointer into a function pointer. This is *not* portable to machines where function pointers and data pointers have different sizes. ``` fn foo() -> i32 { 0 } // Crucially, we `as`-cast to a raw pointer before `transmute`ing to a function pointer. // This avoids an integer-to-pointer `transmute`, which can be problematic. // Transmuting between raw pointers and function pointers (i.e., two pointer types) is fine. let pointer = foo as *const (); let function = unsafe { std::mem::transmute::<*const (), fn() -> i32>(pointer) }; assert_eq!(function(), 0); ``` Extending a lifetime, or shortening an invariant lifetime. This is advanced, very unsafe Rust! ``` struct R<'a>(&'a i32); unsafe fn extend_lifetime<'b>(r: R<'b>) -> R<'static> { std::mem::transmute::<R<'b>, R<'static>>(r) } unsafe fn shorten_invariant_lifetime<'b, 'c>(r: &'b mut R<'static>) -> &'b mut R<'c> { std::mem::transmute::<&'b mut R<'static>, &'b mut R<'c>>(r) } ``` Alternatives ------------ Don’t despair: many uses of `transmute` can be achieved through other means. Below are common applications of `transmute` which can be replaced with safer constructs. Turning raw bytes (`&[u8]`) into `u32`, `f64`, etc.: ``` let raw_bytes = [0x78, 0x56, 0x34, 0x12]; let num = unsafe { std::mem::transmute::<[u8; 4], u32>(raw_bytes) }; // use `u32::from_ne_bytes` instead let num = u32::from_ne_bytes(raw_bytes); // or use `u32::from_le_bytes` or `u32::from_be_bytes` to specify the endianness let num = u32::from_le_bytes(raw_bytes); assert_eq!(num, 0x12345678); let num = u32::from_be_bytes(raw_bytes); assert_eq!(num, 0x78563412); ``` Turning a pointer into a `usize`: ``` let ptr = &0; let ptr_num_transmute = unsafe { std::mem::transmute::<&i32, usize>(ptr) }; // Use an `as` cast instead let ptr_num_cast = ptr as *const i32 as usize; ``` Note that using `transmute` to turn a pointer to a `usize` is (as noted above) [undefined behavior](../../reference/behavior-considered-undefined) in `const` contexts. Also outside of consts, this operation might not behave as expected – this is touching on many unspecified aspects of the Rust memory model. Depending on what the code is doing, the following alternatives are preferable to pointer-to-integer transmutation: * If the code just wants to store data of arbitrary type in some buffer and needs to pick a type for that buffer, it can use [`MaybeUninit`](union.maybeuninit "mem::MaybeUninit"). * If the code actually wants to work on the address the pointer points to, it can use `as` casts or [`ptr.addr()`](../primitive.pointer#method.addr "pointer::addr"). Turning a `*mut T` into an `&mut T`: ``` let ptr: *mut i32 = &mut 0; let ref_transmuted = unsafe { std::mem::transmute::<*mut i32, &mut i32>(ptr) }; // Use a reborrow instead let ref_casted = unsafe { &mut *ptr }; ``` Turning an `&mut T` into an `&mut U`: ``` let ptr = &mut 0; let val_transmuted = unsafe { std::mem::transmute::<&mut i32, &mut u32>(ptr) }; // Now, put together `as` and reborrowing - note the chaining of `as` // `as` is not transitive let val_casts = unsafe { &mut *(ptr as *mut i32 as *mut u32) }; ``` Turning an `&str` into a `&[u8]`: ``` // this is not a good way to do this. let slice = unsafe { std::mem::transmute::<&str, &[u8]>("Rust") }; assert_eq!(slice, &[82, 117, 115, 116]); // You could use `str::as_bytes` let slice = "Rust".as_bytes(); assert_eq!(slice, &[82, 117, 115, 116]); // Or, just use a byte string, if you have control over the string // literal assert_eq!(b"Rust", &[82, 117, 115, 116]); ``` Turning a `Vec<&T>` into a `Vec<Option<&T>>`. To transmute the inner type of the contents of a container, you must make sure to not violate any of the container’s invariants. For `Vec`, this means that both the size *and alignment* of the inner types have to match. Other containers might rely on the size of the type, alignment, or even the `TypeId`, in which case transmuting wouldn’t be possible at all without violating the container invariants. ``` let store = [0, 1, 2, 3]; let v_orig = store.iter().collect::<Vec<&i32>>(); // clone the vector as we will reuse them later let v_clone = v_orig.clone(); // Using transmute: this relies on the unspecified data layout of `Vec`, which is a // bad idea and could cause Undefined Behavior. // However, it is no-copy. let v_transmuted = unsafe { std::mem::transmute::<Vec<&i32>, Vec<Option<&i32>>>(v_clone) }; let v_clone = v_orig.clone(); // This is the suggested, safe way. // It does copy the entire vector, though, into a new array. let v_collected = v_clone.into_iter() .map(Some) .collect::<Vec<Option<&i32>>>(); let v_clone = v_orig.clone(); // This is the proper no-copy, unsafe way of "transmuting" a `Vec`, without relying on the // data layout. Instead of literally calling `transmute`, we perform a pointer cast, but // in terms of converting the original inner type (`&i32`) to the new one (`Option<&i32>`), // this has all the same caveats. Besides the information provided above, also consult the // [`from_raw_parts`] documentation. let v_from_raw = unsafe { // Ensure the original vector is not dropped. let mut v_clone = std::mem::ManuallyDrop::new(v_clone); Vec::from_raw_parts(v_clone.as_mut_ptr() as *mut Option<&i32>, v_clone.len(), v_clone.capacity()) }; ``` Implementing `split_at_mut`: ``` use std::{slice, mem}; // There are multiple ways to do this, and there are multiple problems // with the following (transmute) way. fn split_at_mut_transmute<T>(slice: &mut [T], mid: usize) -> (&mut [T], &mut [T]) { let len = slice.len(); assert!(mid <= len); unsafe { let slice2 = mem::transmute::<&mut [T], &mut [T]>(slice); // first: transmute is not type safe; all it checks is that T and // U are of the same size. Second, right here, you have two // mutable references pointing to the same memory. (&mut slice[0..mid], &mut slice2[mid..len]) } } // This gets rid of the type safety problems; `&mut *` will *only* give // you an `&mut T` from an `&mut T` or `*mut T`. fn split_at_mut_casts<T>(slice: &mut [T], mid: usize) -> (&mut [T], &mut [T]) { let len = slice.len(); assert!(mid <= len); unsafe { let slice2 = &mut *(slice as *mut [T]); // however, you still have two mutable references pointing to // the same memory. (&mut slice[0..mid], &mut slice2[mid..len]) } } // This is how the standard library does it. This is the best method, if // you need to do something like this fn split_at_stdlib<T>(slice: &mut [T], mid: usize) -> (&mut [T], &mut [T]) { let len = slice.len(); assert!(mid <= len); unsafe { let ptr = slice.as_mut_ptr(); // This now has three mutable references pointing at the same // memory. `slice`, the rvalue ret.0, and the rvalue ret.1. // `slice` is never used after `let ptr = ...`, and so one can // treat it as "dead", and therefore, you only have two real // mutable slices. (slice::from_raw_parts_mut(ptr, mid), slice::from_raw_parts_mut(ptr.add(mid), len - mid)) } } ``` rust Function std::mem::take Function std::mem::take ======================= ``` pub fn take<T>(dest: &mut T) -> Twhere    T: Default, ``` Replaces `dest` with the default value of `T`, returning the previous `dest` value. * If you want to replace the values of two variables, see [`swap`](fn.swap "swap"). * If you want to replace with a passed value instead of the default value, see [`replace`](fn.replace "replace"). Examples -------- A simple example: ``` use std::mem; let mut v: Vec<i32> = vec![1, 2]; let old_v = mem::take(&mut v); assert_eq!(vec![1, 2], old_v); assert!(v.is_empty()); ``` `take` allows taking ownership of a struct field by replacing it with an “empty” value. Without `take` you can run into issues like these: ⓘ ``` struct Buffer<T> { buf: Vec<T> } impl<T> Buffer<T> { fn get_and_reset(&mut self) -> Vec<T> { // error: cannot move out of dereference of `&mut`-pointer let buf = self.buf; self.buf = Vec::new(); buf } } ``` Note that `T` does not necessarily implement [`Clone`](../clone/trait.clone "Clone"), so it can’t even clone and reset `self.buf`. But `take` can be used to disassociate the original value of `self.buf` from `self`, allowing it to be returned: ``` use std::mem; impl<T> Buffer<T> { fn get_and_reset(&mut self) -> Vec<T> { mem::take(&mut self.buf) } } let mut buffer = Buffer { buf: vec![0, 1] }; assert_eq!(buffer.buf.len(), 2); assert_eq!(buffer.get_and_reset(), vec![0, 1]); assert_eq!(buffer.buf.len(), 0); ``` rust Function std::mem::drop Function std::mem::drop ======================= ``` pub fn drop<T>(_x: T) ``` Disposes of a value. This does so by calling the argument’s implementation of [`Drop`](../ops/trait.drop). This effectively does nothing for types which implement `Copy`, e.g. integers. Such values are copied and *then* moved into the function, so the value persists after this function call. This function is not magic; it is literally defined as ``` pub fn drop<T>(_x: T) { } ``` Because `_x` is moved into the function, it is automatically dropped before the function returns. Examples -------- Basic usage: ``` let v = vec![1, 2, 3]; drop(v); // explicitly drop the vector ``` Since [`RefCell`](../cell/struct.refcell) enforces the borrow rules at runtime, `drop` can release a [`RefCell`](../cell/struct.refcell) borrow: ``` use std::cell::RefCell; let x = RefCell::new(1); let mut mutable_borrow = x.borrow_mut(); *mutable_borrow = 1; drop(mutable_borrow); // relinquish the mutable borrow on this slot let borrow = x.borrow(); println!("{}", *borrow); ``` Integers and other types implementing [`Copy`](../marker/trait.copy "Copy") are unaffected by `drop`. ``` #[derive(Copy, Clone)] struct Foo(u8); let x = 1; let y = Foo(2); drop(x); // a copy of `x` is moved and dropped drop(y); // a copy of `y` is moved and dropped println!("x: {}, y: {}", x, y.0); // still available ``` rust Function std::mem::needs_drop Function std::mem::needs\_drop ============================== ``` pub const fn needs_drop<T>() -> boolwhere    T: ?Sized, ``` Returns `true` if dropping values of type `T` matters. This is purely an optimization hint, and may be implemented conservatively: it may return `true` for types that don’t actually need to be dropped. As such always returning `true` would be a valid implementation of this function. However if this function actually returns `false`, then you can be certain dropping `T` has no side effect. Low level implementations of things like collections, which need to manually drop their data, should use this function to avoid unnecessarily trying to drop all their contents when they are destroyed. This might not make a difference in release builds (where a loop that has no side-effects is easily detected and eliminated), but is often a big win for debug builds. Note that [`drop_in_place`](../ptr/fn.drop_in_place) already performs this check, so if your workload can be reduced to some small number of [`drop_in_place`](../ptr/fn.drop_in_place) calls, using this is unnecessary. In particular note that you can [`drop_in_place`](../ptr/fn.drop_in_place) a slice, and that will do a single needs\_drop check for all the values. Types like Vec therefore just `drop_in_place(&mut self[..])` without using `needs_drop` explicitly. Types like [`HashMap`](../collections/struct.hashmap), on the other hand, have to drop values one at a time and should use this API. Examples -------- Here’s an example of how a collection might make use of `needs_drop`: ``` use std::{mem, ptr}; pub struct MyCollection<T> { /* ... */ } impl<T> Drop for MyCollection<T> { fn drop(&mut self) { unsafe { // drop the data if mem::needs_drop::<T>() { for x in self.iter_mut() { ptr::drop_in_place(x); } } self.free_buffer(); } } } ```
programming_docs
rust Struct std::mem::Discriminant Struct std::mem::Discriminant ============================= ``` pub struct Discriminant<T>(_); ``` Opaque type representing the discriminant of an enum. See the [`discriminant`](fn.discriminant "discriminant") function in this module for more information. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/mem/mod.rs.html#1084)### impl<T> Clone for Discriminant<T> [source](https://doc.rust-lang.org/src/core/mem/mod.rs.html#1085)#### fn clone(&self) -> Discriminant<T> Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/mem/mod.rs.html#1108)### impl<T> Debug for Discriminant<T> [source](https://doc.rust-lang.org/src/core/mem/mod.rs.html#1109)#### fn fmt(&self, fmt: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/mem/mod.rs.html#1101)### impl<T> Hash for Discriminant<T> [source](https://doc.rust-lang.org/src/core/mem/mod.rs.html#1102)#### fn hash<H>(&self, state: &mut H)where H: [Hasher](../hash/trait.hasher "trait std::hash::Hasher"), Feeds this value into the given [`Hasher`](../hash/trait.hasher "Hasher"). [Read more](../hash/trait.hash#tymethod.hash) [source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0 · #### fn hash\_slice<H>(data: &[Self], state: &mut H)where H: [Hasher](../hash/trait.hasher "trait std::hash::Hasher"), Feeds a slice of this type into the given [`Hasher`](../hash/trait.hasher "Hasher"). [Read more](../hash/trait.hash#method.hash_slice) [source](https://doc.rust-lang.org/src/core/mem/mod.rs.html#1091)### impl<T> PartialEq<Discriminant<T>> for Discriminant<T> [source](https://doc.rust-lang.org/src/core/mem/mod.rs.html#1092)#### fn eq(&self, rhs: &Discriminant<T>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)1.0.0 · #### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/core/mem/mod.rs.html#1081)### impl<T> Copy for Discriminant<T> [source](https://doc.rust-lang.org/src/core/mem/mod.rs.html#1098)### impl<T> Eq for Discriminant<T> Auto Trait Implementations -------------------------- ### impl<T> RefUnwindSafe for Discriminant<T>where <T as [DiscriminantKind](../marker/trait.discriminantkind "trait std::marker::DiscriminantKind")>::[Discriminant](../marker/trait.discriminantkind#associatedtype.Discriminant "type std::marker::DiscriminantKind::Discriminant"): [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<T> Send for Discriminant<T> ### impl<T> Sync for Discriminant<T> ### impl<T> Unpin for Discriminant<T> ### impl<T> UnwindSafe for Discriminant<T>where <T as [DiscriminantKind](../marker/trait.discriminantkind "trait std::marker::DiscriminantKind")>::[Discriminant](../marker/trait.discriminantkind#associatedtype.Discriminant "type std::marker::DiscriminantKind::Discriminant"): [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Function std::mem::swap Function std::mem::swap ======================= ``` pub fn swap<T>(x: &mut T, y: &mut T) ``` Swaps the values at two mutable locations, without deinitializing either one. * If you want to swap with a default or dummy value, see [`take`](fn.take "take"). * If you want to swap with a passed value, returning the old value, see [`replace`](fn.replace "replace"). Examples -------- ``` use std::mem; let mut x = 5; let mut y = 42; mem::swap(&mut x, &mut y); assert_eq!(42, x); assert_eq!(5, y); ``` rust Function std::mem::variant_count Function std::mem::variant\_count ================================= ``` pub fn variant_count<T>() -> usize ``` 🔬This is a nightly-only experimental API. (`variant_count` [#73662](https://github.com/rust-lang/rust/issues/73662)) Returns the number of variants in the enum type `T`. If `T` is not an enum, calling this function will not result in undefined behavior, but the return value is unspecified. Equally, if `T` is an enum with more variants than `usize::MAX` the return value is unspecified. Uninhabited variants will be counted. Note that an enum may be expanded with additional variants in the future as a non-breaking change, for example if it is marked `#[non_exhaustive]`, which will change the result of this function. Examples -------- ``` use std::mem; enum Void {} enum Foo { A(&'static str), B(i32), C(i32) } assert_eq!(mem::variant_count::<Void>(), 0); assert_eq!(mem::variant_count::<Foo>(), 3); assert_eq!(mem::variant_count::<Option<!>>(), 2); assert_eq!(mem::variant_count::<Result<!, !>>(), 2); ``` rust Function std::mem::size_of Function std::mem::size\_of =========================== ``` pub const fn size_of<T>() -> usize ``` Returns the size of a type in bytes. More specifically, this is the offset in bytes between successive elements in an array with that item type including alignment padding. Thus, for any type `T` and length `n`, `[T; n]` has a size of `n * size_of::<T>()`. In general, the size of a type is not stable across compilations, but specific types such as primitives are. The following table gives the size for primitives. | Type | size\_of::<Type>() | | --- | --- | | () | 0 | | bool | 1 | | u8 | 1 | | u16 | 2 | | u32 | 4 | | u64 | 8 | | u128 | 16 | | i8 | 1 | | i16 | 2 | | i32 | 4 | | i64 | 8 | | i128 | 16 | | f32 | 4 | | f64 | 8 | | char | 4 | Furthermore, `usize` and `isize` have the same size. The types `*const T`, `&T`, `Box<T>`, `Option<&T>`, and `Option<Box<T>>` all have the same size. If `T` is Sized, all of those types have the same size as `usize`. The mutability of a pointer does not change its size. As such, `&T` and `&mut T` have the same size. Likewise for `*const T` and `*mut T`. Size of `#[repr(C)]` items -------------------------- The `C` representation for items has a defined layout. With this layout, the size of items is also stable as long as all fields have a stable size. ### Size of Structs For `structs`, the size is determined by the following algorithm. For each field in the struct ordered by declaration order: 1. Add the size of the field. 2. Round up the current size to the nearest multiple of the next field’s [alignment](fn.align_of). Finally, round the size of the struct to the nearest multiple of its [alignment](fn.align_of). The alignment of the struct is usually the largest alignment of all its fields; this can be changed with the use of `repr(align(N))`. Unlike `C`, zero sized structs are not rounded up to one byte in size. ### Size of Enums Enums that carry no data other than the discriminant have the same size as C enums on the platform they are compiled for. ### Size of Unions The size of a union is the size of its largest field. Unlike `C`, zero sized unions are not rounded up to one byte in size. Examples -------- ``` use std::mem; // Some primitives assert_eq!(4, mem::size_of::<i32>()); assert_eq!(8, mem::size_of::<f64>()); assert_eq!(0, mem::size_of::<()>()); // Some arrays assert_eq!(8, mem::size_of::<[i32; 2]>()); assert_eq!(12, mem::size_of::<[i32; 3]>()); assert_eq!(0, mem::size_of::<[i32; 0]>()); // Pointer size equality assert_eq!(mem::size_of::<&i32>(), mem::size_of::<*const i32>()); assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Box<i32>>()); assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Option<&i32>>()); assert_eq!(mem::size_of::<Box<i32>>(), mem::size_of::<Option<Box<i32>>>()); ``` Using `#[repr(C)]`. ``` use std::mem; #[repr(C)] struct FieldStruct { first: u8, second: u16, third: u8 } // The size of the first field is 1, so add 1 to the size. Size is 1. // The alignment of the second field is 2, so add 1 to the size for padding. Size is 2. // The size of the second field is 2, so add 2 to the size. Size is 4. // The alignment of the third field is 1, so add 0 to the size for padding. Size is 4. // The size of the third field is 1, so add 1 to the size. Size is 5. // Finally, the alignment of the struct is 2 (because the largest alignment amongst its // fields is 2), so add 1 to the size for padding. Size is 6. assert_eq!(6, mem::size_of::<FieldStruct>()); #[repr(C)] struct TupleStruct(u8, u16, u8); // Tuple structs follow the same rules. assert_eq!(6, mem::size_of::<TupleStruct>()); // Note that reordering the fields can lower the size. We can remove both padding bytes // by putting `third` before `second`. #[repr(C)] struct FieldStructOptimized { first: u8, third: u8, second: u16 } assert_eq!(4, mem::size_of::<FieldStructOptimized>()); // Union size is the size of the largest field. #[repr(C)] union ExampleUnion { smaller: u8, larger: u16 } assert_eq!(2, mem::size_of::<ExampleUnion>()); ``` rust Function std::mem::transmute_copy Function std::mem::transmute\_copy ================================== ``` pub unsafe fn transmute_copy<T, U>(src: &T) -> U ``` Interprets `src` as having type `&U`, and then reads `src` without moving the contained value. This function will unsafely assume the pointer `src` is valid for [`size_of::<U>`](fn.size_of "size_of") bytes by transmuting `&T` to `&U` and then reading the `&U` (except that this is done in a way that is correct even when `&U` has stricter alignment requirements than `&T`). It will also unsafely create a copy of the contained value instead of moving out of `src`. It is not a compile-time error if `T` and `U` have different sizes, but it is highly encouraged to only invoke this function where `T` and `U` have the same size. This function triggers [undefined behavior](../../reference/behavior-considered-undefined) if `U` is larger than `T`. Examples -------- ``` use std::mem; #[repr(packed)] struct Foo { bar: u8, } let foo_array = [10u8]; unsafe { // Copy the data from 'foo_array' and treat it as a 'Foo' let mut foo_struct: Foo = mem::transmute_copy(&foo_array); assert_eq!(foo_struct.bar, 10); // Modify the copied data foo_struct.bar = 20; assert_eq!(foo_struct.bar, 20); } // The contents of 'foo_array' should not have changed assert_eq!(foo_array, [10]); ``` rust Function std::mem::size_of_val_raw Function std::mem::size\_of\_val\_raw ===================================== ``` pub unsafe fn size_of_val_raw<T>(val: *const T) -> usizewhere    T: ?Sized, ``` 🔬This is a nightly-only experimental API. (`layout_for_ptr` [#69835](https://github.com/rust-lang/rust/issues/69835)) Returns the size of the pointed-to value in bytes. This is usually the same as `size_of::<T>()`. However, when `T` *has* no statically-known size, e.g., a slice [`[T]`](../primitive.slice "slice") or a [trait object](../../book/ch17-02-trait-objects), then `size_of_val_raw` can be used to get the dynamically-known size. Safety ------ This function is only safe to call if the following conditions hold: * If `T` is `Sized`, this function is always safe to call. * If the unsized tail of `T` is: + a [slice](../primitive.slice "slice"), then the length of the slice tail must be an initialized integer, and the size of the *entire value* (dynamic tail length + statically sized prefix) must fit in `isize`. + a [trait object](../../book/ch17-02-trait-objects), then the vtable part of the pointer must point to a valid vtable acquired by an unsizing coercion, and the size of the *entire value* (dynamic tail length + statically sized prefix) must fit in `isize`. + an (unstable) [extern type](https://doc.rust-lang.org/unstable-book/language-features/extern-types.html), then this function is always safe to call, but may panic or otherwise return the wrong value, as the extern type’s layout is not known. This is the same behavior as [`size_of_val`](fn.size_of_val "size_of_val") on a reference to a type with an extern type tail. + otherwise, it is conservatively not allowed to call this function. Examples -------- ``` #![feature(layout_for_ptr)] use std::mem; assert_eq!(4, mem::size_of_val(&5i32)); let x: [u8; 13] = [0; 13]; let y: &[u8] = &x; assert_eq!(13, unsafe { mem::size_of_val_raw(y) }); ``` rust Function std::mem::min_align_of Function std::mem::min\_align\_of ================================= ``` pub fn min_align_of<T>() -> usize ``` 👎Deprecated since 1.2.0: use `align_of` instead Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface)-required minimum alignment of a type in bytes. Every reference to a value of the type `T` must be a multiple of this number. This is the alignment used for struct fields. It may be smaller than the preferred alignment. Examples -------- ``` use std::mem; assert_eq!(4, mem::min_align_of::<i32>()); ``` rust Function std::mem::discriminant Function std::mem::discriminant =============================== ``` pub fn discriminant<T>(v: &T) -> Discriminant<T> ``` Returns a value uniquely identifying the enum variant in `v`. If `T` is not an enum, calling this function will not result in undefined behavior, but the return value is unspecified. Stability --------- The discriminant of an enum variant may change if the enum definition changes. A discriminant of some variant will not change between compilations with the same compiler. Examples -------- This can be used to compare enums that carry data, while disregarding the actual data: ``` use std::mem; enum Foo { A(&'static str), B(i32), C(i32) } assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz"))); assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2))); assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3))); ``` rust Struct std::mem::ManuallyDrop Struct std::mem::ManuallyDrop ============================= ``` #[repr(transparent)]pub struct ManuallyDrop<T>where    T: ?Sized,{ /* private fields */ } ``` A wrapper to inhibit compiler from automatically calling `T`’s destructor. This wrapper is 0-cost. `ManuallyDrop<T>` is guaranteed to have the same layout as `T`, and is subject to the same layout optimizations as `T`. As a consequence, it has *no effect* on the assumptions that the compiler makes about its contents. For example, initializing a `ManuallyDrop<&mut T>` with [`mem::zeroed`](fn.zeroed) is undefined behavior. If you need to handle uninitialized data, use [`MaybeUninit<T>`](union.maybeuninit) instead. Note that accessing the value inside a `ManuallyDrop<T>` is safe. This means that a `ManuallyDrop<T>` whose content has been dropped must not be exposed through a public safe API. Correspondingly, `ManuallyDrop::drop` is unsafe. `ManuallyDrop` and drop order. ------------------------------- Rust has a well-defined [drop order](../../reference/destructors) of values. To make sure that fields or locals are dropped in a specific order, reorder the declarations such that the implicit drop order is the correct one. It is possible to use `ManuallyDrop` to control the drop order, but this requires unsafe code and is hard to do correctly in the presence of unwinding. For example, if you want to make sure that a specific field is dropped after the others, make it the last field of a struct: ``` struct Context; struct Widget { children: Vec<Widget>, // `context` will be dropped after `children`. // Rust guarantees that fields are dropped in the order of declaration. context: Context, } ``` Implementations --------------- [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#54)### impl<T> ManuallyDrop<T> [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#70)const: 1.32.0 · #### pub const fn new(value: T) -> ManuallyDrop<T> Wrap a value to be manually dropped. ##### Examples ``` use std::mem::ManuallyDrop; let mut x = ManuallyDrop::new(String::from("Hello World!")); x.truncate(5); // You can still safely operate on the value assert_eq!(*x, "Hello"); // But `Drop` will not be run here ``` [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#88)const: 1.32.0 · #### pub const fn into\_inner(slot: ManuallyDrop<T>) -> T Extracts the value from the `ManuallyDrop` container. This allows the value to be dropped again. ##### Examples ``` use std::mem::ManuallyDrop; let x = ManuallyDrop::new(Box::new(())); let _: Box<()> = ManuallyDrop::into_inner(x); // This drops the `Box`. ``` [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#110)1.42.0 · #### pub unsafe fn take(slot: &mut ManuallyDrop<T>) -> T Takes the value from the `ManuallyDrop<T>` container out. This method is primarily intended for moving out values in drop. Instead of using [`ManuallyDrop::drop`](struct.manuallydrop#method.drop "ManuallyDrop::drop") to manually drop the value, you can use this method to take the value and use it however desired. Whenever possible, it is preferable to use [`into_inner`](struct.manuallydrop#method.into_inner "ManuallyDrop::into_inner") instead, which prevents duplicating the content of the `ManuallyDrop<T>`. ##### Safety This function semantically moves out the contained value without preventing further usage, leaving the state of this container unchanged. It is your responsibility to ensure that this `ManuallyDrop` is not used again. [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#117)### impl<T> ManuallyDrop<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#140)#### pub unsafe fn drop(slot: &mut ManuallyDrop<T>) Manually drops the contained value. This is exactly equivalent to calling [`ptr::drop_in_place`](../ptr/fn.drop_in_place "ptr::drop_in_place") with a pointer to the contained value. As such, unless the contained value is a packed struct, the destructor will be called in-place without moving the value, and thus can be used to safely drop [pinned](../pin/index) data. If you have ownership of the value, you can use [`ManuallyDrop::into_inner`](struct.manuallydrop#method.into_inner "ManuallyDrop::into_inner") instead. ##### Safety This function runs the destructor of the contained value. Other than changes made by the destructor itself, the memory is left unchanged, and so as far as the compiler is concerned still holds a bit-pattern which is valid for the type `T`. However, this “zombie” value should not be exposed to safe code, and this function should not be called more than once. To use a value after it’s been dropped, or drop a value multiple times, can cause Undefined Behavior (depending on what `drop` does). This is normally prevented by the type system, but users of `ManuallyDrop` must uphold those guarantees without assistance from the compiler. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)### impl<T> Clone for ManuallyDrop<T>where T: [Clone](../clone/trait.clone "trait std::clone::Clone") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)#### fn clone(&self) -> ManuallyDrop<T> Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)### impl<T> Debug for ManuallyDrop<T>where T: [Debug](../fmt/trait.debug "trait std::fmt::Debug") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)### impl<T> Default for ManuallyDrop<T>where T: [Default](../default/trait.default "trait std::default::Default") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)#### fn default() -> ManuallyDrop<T> Returns the “default value” for a type. [Read more](../default/trait.default#tymethod.default) [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#150)const: [unstable](https://github.com/rust-lang/rust/issues/88955 "Tracking issue for const_deref") · ### impl<T> Deref for ManuallyDrop<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), #### type Target = T The resulting type after dereferencing. [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#153)const: [unstable](https://github.com/rust-lang/rust/issues/88955 "Tracking issue for const_deref") · #### fn deref(&self) -> &T Dereferences the value. [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#160)const: [unstable](https://github.com/rust-lang/rust/issues/88955 "Tracking issue for const_deref") · ### impl<T> DerefMut for ManuallyDrop<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#162)const: [unstable](https://github.com/rust-lang/rust/issues/88955 "Tracking issue for const_deref") · #### fn deref\_mut(&mut self) -> &mut T Mutably dereferences the value. [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)### impl<T> Hash for ManuallyDrop<T>where T: [Hash](../hash/trait.hash "trait std::hash::Hash") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)#### fn hash<\_\_H>(&self, state: &mut \_\_H)where \_\_H: [Hasher](../hash/trait.hasher "trait std::hash::Hasher"), Feeds this value into the given [`Hasher`](../hash/trait.hasher "Hasher"). [Read more](../hash/trait.hash#tymethod.hash) [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)### impl<T> Ord for ManuallyDrop<T>where T: [Ord](../cmp/trait.ord "trait std::cmp::Ord") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)#### fn cmp(&self, other: &ManuallyDrop<T>) -> Ordering This method returns an [`Ordering`](../cmp/enum.ordering "Ordering") between `self` and `other`. [Read more](../cmp/trait.ord#tymethod.cmp) [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)### impl<T> PartialEq<ManuallyDrop<T>> for ManuallyDrop<T>where T: [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<T> + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)#### fn eq(&self, other: &ManuallyDrop<T>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)1.0.0 · #### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)### impl<T> PartialOrd<ManuallyDrop<T>> for ManuallyDrop<T>where T: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<T> + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)#### fn partial\_cmp(&self, other: &ManuallyDrop<T>) -> Option<Ordering> This method returns an ordering between `self` and `other` values if one exists. [Read more](../cmp/trait.partialord#tymethod.partial_cmp) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1138)1.0.0 · #### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](../cmp/trait.partialord#method.lt) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1157)1.0.0 · #### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](../cmp/trait.partialord#method.le) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1175)1.0.0 · #### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](../cmp/trait.partialord#method.gt) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1194)1.0.0 · #### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](../cmp/trait.partialord#method.ge) [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)### impl<T> Copy for ManuallyDrop<T>where T: [Copy](../marker/trait.copy "trait std::marker::Copy") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)### impl<T> Eq for ManuallyDrop<T>where T: [Eq](../cmp/trait.eq "trait std::cmp::Eq") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)### impl<T> StructuralEq for ManuallyDrop<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/mem/manually_drop.rs.html#48)### impl<T> StructuralPartialEq for ManuallyDrop<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), Auto Trait Implementations -------------------------- ### impl<T: ?Sized> RefUnwindSafe for ManuallyDrop<T>where T: [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<T: ?Sized> Send for ManuallyDrop<T>where T: [Send](../marker/trait.send "trait std::marker::Send"), ### impl<T: ?Sized> Sync for ManuallyDrop<T>where T: [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<T: ?Sized> Unpin for ManuallyDrop<T>where T: [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), ### impl<T: ?Sized> UnwindSafe for ManuallyDrop<T>where T: [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Function std::mem::forget Function std::mem::forget ========================= ``` pub const fn forget<T>(t: T) ``` Takes ownership and “forgets” about the value **without running its destructor**. Any resources the value manages, such as heap memory or a file handle, will linger forever in an unreachable state. However, it does not guarantee that pointers to this memory will remain valid. * If you want to leak memory, see [`Box::leak`](../boxed/struct.box#method.leak). * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`](../boxed/struct.box#method.into_raw). * If you want to dispose of a value properly, running its destructor, see [`mem::drop`](fn.drop). Safety ------ `forget` is not marked as `unsafe`, because Rust’s safety guarantees do not include a guarantee that destructors will always run. For example, a program can create a reference cycle using [`Rc`](../rc/struct.rc), or call [`process::exit`](../process/fn.exit) to exit without running destructors. Thus, allowing `mem::forget` from safe code does not fundamentally change Rust’s safety guarantees. That said, leaking resources such as memory or I/O objects is usually undesirable. The need comes up in some specialized use cases for FFI or unsafe code, but even then, [`ManuallyDrop`](struct.manuallydrop "ManuallyDrop") is typically preferred. Because forgetting a value is allowed, any `unsafe` code you write must allow for this possibility. You cannot return a value and expect that the caller will necessarily run the value’s destructor. Examples -------- The canonical safe use of `mem::forget` is to circumvent a value’s destructor implemented by the `Drop` trait. For example, this will leak a `File`, i.e. reclaim the space taken by the variable but never close the underlying system resource: ``` use std::mem; use std::fs::File; let file = File::open("foo.txt").unwrap(); mem::forget(file); ``` This is useful when the ownership of the underlying resource was previously transferred to code outside of Rust, for example by transmitting the raw file descriptor to C code. Relationship with `ManuallyDrop` -------------------------------- While `mem::forget` can also be used to transfer *memory* ownership, doing so is error-prone. [`ManuallyDrop`](struct.manuallydrop "ManuallyDrop") should be used instead. Consider, for example, this code: ``` use std::mem; let mut v = vec![65, 122]; // Build a `String` using the contents of `v` let s = unsafe { String::from_raw_parts(v.as_mut_ptr(), v.len(), v.capacity()) }; // leak `v` because its memory is now managed by `s` mem::forget(v); // ERROR - v is invalid and must not be passed to a function assert_eq!(s, "Az"); // `s` is implicitly dropped and its memory deallocated. ``` There are two issues with the above example: * If more code were added between the construction of `String` and the invocation of `mem::forget()`, a panic within it would cause a double free because the same memory is handled by both `v` and `s`. * After calling `v.as_mut_ptr()` and transmitting the ownership of the data to `s`, the `v` value is invalid. Even when a value is just moved to `mem::forget` (which won’t inspect it), some types have strict requirements on their values that make them invalid when dangling or no longer owned. Using invalid values in any way, including passing them to or returning them from functions, constitutes undefined behavior and may break the assumptions made by the compiler. Switching to `ManuallyDrop` avoids both issues: ``` use std::mem::ManuallyDrop; let v = vec![65, 122]; // Before we disassemble `v` into its raw parts, make sure it // does not get dropped! let mut v = ManuallyDrop::new(v); // Now disassemble `v`. These operations cannot panic, so there cannot be a leak. let (ptr, len, cap) = (v.as_mut_ptr(), v.len(), v.capacity()); // Finally, build a `String`. let s = unsafe { String::from_raw_parts(ptr, len, cap) }; assert_eq!(s, "Az"); // `s` is implicitly dropped and its memory deallocated. ``` `ManuallyDrop` robustly prevents double-free because we disable `v`’s destructor before doing anything else. `mem::forget()` doesn’t allow this because it consumes its argument, forcing us to call it only after extracting anything we need from `v`. Even if a panic were introduced between construction of `ManuallyDrop` and building the string (which cannot happen in the code as shown), it would result in a leak and not a double free. In other words, `ManuallyDrop` errs on the side of leaking instead of erring on the side of (double-)dropping. Also, `ManuallyDrop` prevents us from having to “touch” `v` after transferring the ownership to `s` — the final step of interacting with `v` to dispose of it without running its destructor is entirely avoided. rust Function std::mem::forget_unsized Function std::mem::forget\_unsized ================================== ``` pub fn forget_unsized<T>(t: T)where    T: ?Sized, ``` 🔬This is a nightly-only experimental API. (`forget_unsized`) Like [`forget`](fn.forget "forget"), but also accepts unsized values. This function is just a shim intended to be removed when the `unsized_locals` feature gets stabilized. rust Function std::mem::replace Function std::mem::replace ========================== ``` pub fn replace<T>(dest: &mut T, src: T) -> T ``` Moves `src` into the referenced `dest`, returning the previous `dest` value. Neither value is dropped. * If you want to replace the values of two variables, see [`swap`](fn.swap "swap"). * If you want to replace with a default value, see [`take`](fn.take "take"). Examples -------- A simple example: ``` use std::mem; let mut v: Vec<i32> = vec![1, 2]; let old_v = mem::replace(&mut v, vec![3, 4, 5]); assert_eq!(vec![1, 2], old_v); assert_eq!(vec![3, 4, 5], v); ``` `replace` allows consumption of a struct field by replacing it with another value. Without `replace` you can run into issues like these: ⓘ ``` struct Buffer<T> { buf: Vec<T> } impl<T> Buffer<T> { fn replace_index(&mut self, i: usize, v: T) -> T { // error: cannot move out of dereference of `&mut`-pointer let t = self.buf[i]; self.buf[i] = v; t } } ``` Note that `T` does not necessarily implement [`Clone`](../clone/trait.clone "Clone"), so we can’t even clone `self.buf[i]` to avoid the move. But `replace` can be used to disassociate the original value at that index from `self`, allowing it to be returned: ``` use std::mem; impl<T> Buffer<T> { fn replace_index(&mut self, i: usize, v: T) -> T { mem::replace(&mut self.buf[i], v) } } let mut buffer = Buffer { buf: vec![0, 1] }; assert_eq!(buffer.buf[0], 0); assert_eq!(buffer.replace_index(0, 2), 0); assert_eq!(buffer.buf[0], 2); ``` rust Struct std::mem::Assume Struct std::mem::Assume ======================= ``` pub struct Assume { pub alignment: bool, pub lifetimes: bool, pub safety: bool, pub validity: bool, } ``` 🔬This is a nightly-only experimental API. (`transmutability` [#99571](https://github.com/rust-lang/rust/issues/99571)) What transmutation safety conditions shall the compiler assume that *you* are checking? Fields ------ `alignment: [bool](../primitive.bool)` 🔬This is a nightly-only experimental API. (`transmutability` [#99571](https://github.com/rust-lang/rust/issues/99571)) When `true`, the compiler assumes that *you* are ensuring (either dynamically or statically) that destination referents do not have stricter alignment requirements than source referents. `lifetimes: [bool](../primitive.bool)` 🔬This is a nightly-only experimental API. (`transmutability` [#99571](https://github.com/rust-lang/rust/issues/99571)) When `true`, the compiler assume that *you* are ensuring that lifetimes are not extended in a manner that violates Rust’s memory model. `safety: [bool](../primitive.bool)` 🔬This is a nightly-only experimental API. (`transmutability` [#99571](https://github.com/rust-lang/rust/issues/99571)) When `true`, the compiler assumes that *you* have ensured that it is safe for you to violate the type and field privacy of the destination type (and sometimes of the source type, too). `validity: [bool](../primitive.bool)` 🔬This is a nightly-only experimental API. (`transmutability` [#99571](https://github.com/rust-lang/rust/issues/99571)) When `true`, the compiler assumes that *you* are ensuring that the source type is actually a valid instance of the destination type. Implementations --------------- [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#40)### impl Assume [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#43)#### pub const NOTHING: Assume = Self{ alignment: false, lifetimes: false, safety: false, validity: false,} 🔬This is a nightly-only experimental API. (`transmutability` [#99571](https://github.com/rust-lang/rust/issues/99571)) Do not assume that *you* have ensured any safety properties are met. [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#48)#### pub const ALIGNMENT: Assume = Self{ alignment: true, ..Self::NOTHING} 🔬This is a nightly-only experimental API. (`transmutability` [#99571](https://github.com/rust-lang/rust/issues/99571)) Assume only that alignment conditions are met. [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#52)#### pub const LIFETIMES: Assume = Self{ lifetimes: true, ..Self::NOTHING} 🔬This is a nightly-only experimental API. (`transmutability` [#99571](https://github.com/rust-lang/rust/issues/99571)) Assume only that lifetime conditions are met. [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#56)#### pub const SAFETY: Assume = Self{ safety: true, ..Self::NOTHING} 🔬This is a nightly-only experimental API. (`transmutability` [#99571](https://github.com/rust-lang/rust/issues/99571)) Assume only that safety conditions are met. [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#60)#### pub const VALIDITY: Assume = Self{ validity: true, ..Self::NOTHING} 🔬This is a nightly-only experimental API. (`transmutability` [#99571](https://github.com/rust-lang/rust/issues/99571)) Assume only that dynamically-satisfiable validity conditions are met. [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#64)#### pub const fn and(self, other\_assumptions: Assume) -> Assume 🔬This is a nightly-only experimental API. (`transmutability` [#99571](https://github.com/rust-lang/rust/issues/99571)) Assume both `self` and `other_assumptions`. [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#75)#### pub const fn but\_not(self, other\_assumptions: Assume) -> Assume 🔬This is a nightly-only experimental API. (`transmutability` [#99571](https://github.com/rust-lang/rust/issues/99571)) Assume `self`, excepting `other_assumptions`. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#89)const: [unstable](https://github.com/rust-lang/rust/issues/99571 "Tracking issue for transmutability") · ### impl Add<Assume> for Assume #### type Output = Assume The resulting type after applying the `+` operator. [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#92)const: [unstable](https://github.com/rust-lang/rust/issues/99571 "Tracking issue for transmutability") · #### fn add(self, other\_assumptions: Assume) -> Assume Performs the `+` operation. [Read more](../ops/trait.add#tymethod.add) [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#21)### impl Clone for Assume [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#21)#### fn clone(&self) -> Assume Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#21)### impl Debug for Assume [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#21)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#21)### impl PartialEq<Assume> for Assume [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#21)#### fn eq(&self, other: &Assume) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)1.0.0 · #### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#101)const: [unstable](https://github.com/rust-lang/rust/issues/99571 "Tracking issue for transmutability") · ### impl Sub<Assume> for Assume #### type Output = Assume The resulting type after applying the `-` operator. [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#104)const: [unstable](https://github.com/rust-lang/rust/issues/99571 "Tracking issue for transmutability") · #### fn sub(self, other\_assumptions: Assume) -> Assume Performs the `-` operation. [Read more](../ops/trait.sub#tymethod.sub) [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#21)### impl Copy for Assume [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#21)### impl Eq for Assume [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#21)### impl StructuralEq for Assume [source](https://doc.rust-lang.org/src/core/mem/transmutability.rs.html#21)### impl StructuralPartialEq for Assume Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for Assume ### impl Send for Assume ### impl Sync for Assume ### impl Unpin for Assume ### impl UnwindSafe for Assume Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Function std::mem::align_of Function std::mem::align\_of ============================ ``` pub const fn align_of<T>() -> usize ``` Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface)-required minimum alignment of a type in bytes. Every reference to a value of the type `T` must be a multiple of this number. This is the alignment used for struct fields. It may be smaller than the preferred alignment. Examples -------- ``` use std::mem; assert_eq!(4, mem::align_of::<i32>()); ``` rust Function std::mem::zeroed Function std::mem::zeroed ========================= ``` pub unsafe fn zeroed<T>() -> T ``` Returns the value of type `T` represented by the all-zero byte-pattern. This means that, for example, the padding byte in `(u8, u16)` is not necessarily zeroed. There is no guarantee that an all-zero byte-pattern represents a valid value of some type `T`. For example, the all-zero byte-pattern is not a valid value for reference types (`&T`, `&mut T`) and functions pointers. Using `zeroed` on such types causes immediate [undefined behavior](../../reference/behavior-considered-undefined) because [the Rust compiler assumes](union.maybeuninit#initialization-invariant) that there always is a valid value in a variable it considers initialized. This has the same effect as [`MaybeUninit::zeroed().assume_init()`](union.maybeuninit#method.zeroed). It is useful for FFI sometimes, but should generally be avoided. Examples -------- Correct usage of this function: initializing an integer with zero. ``` use std::mem; let x: i32 = unsafe { mem::zeroed() }; assert_eq!(0, x); ``` *Incorrect* usage of this function: initializing a reference with zero. ``` use std::mem; let _x: &i32 = unsafe { mem::zeroed() }; // Undefined behavior! let _y: fn() = unsafe { mem::zeroed() }; // And again! ```
programming_docs
rust Function std::mem::copy Function std::mem::copy ======================= ``` pub fn copy<T>(x: &T) -> Twhere    T: Copy, ``` 🔬This is a nightly-only experimental API. (`mem_copy_fn` [#98262](https://github.com/rust-lang/rust/issues/98262)) Bitwise-copies a value. This function is not magic; it is literally defined as ``` pub fn copy<T: Copy>(x: &T) -> T { *x } ``` It is useful when you want to pass a function pointer to a combinator, rather than defining a new closure. Example: ``` #![feature(mem_copy_fn)] use core::mem::copy; let result_from_ffi_function: Result<(), &i32> = Err(&1); let result_copied: Result<(), i32> = result_from_ffi_function.map_err(copy); ``` rust Trait std::mem::BikeshedIntrinsicFrom Trait std::mem::BikeshedIntrinsicFrom ===================================== ``` pub unsafe trait BikeshedIntrinsicFrom<Src, Context, const ASSUME: Assume = _>where    Src: ?Sized,{ } ``` 🔬This is a nightly-only experimental API. (`transmutability` [#99571](https://github.com/rust-lang/rust/issues/99571)) Are values of a type transmutable into values of another type? This trait is implemented on-the-fly by the compiler for types `Src` and `Self` when the bits of any value of type `Self` are safely transmutable into a value of type `Dst`, in a given `Context`, notwithstanding whatever safety checks you have asked the compiler to [`Assume`](struct.assume "Assume") are satisfied. Implementors ------------ rust Union std::mem::MaybeUninit Union std::mem::MaybeUninit =========================== ``` #[repr(transparent)] pub union MaybeUninit<T> { /* private fields */ } ``` A wrapper type to construct uninitialized instances of `T`. Initialization invariant ------------------------ The compiler, in general, assumes that a variable is properly initialized according to the requirements of the variable’s type. For example, a variable of reference type must be aligned and non-null. This is an invariant that must *always* be upheld, even in unsafe code. As a consequence, zero-initializing a variable of reference type causes instantaneous [undefined behavior](../../reference/behavior-considered-undefined), no matter whether that reference ever gets used to access memory: ``` use std::mem::{self, MaybeUninit}; let x: &i32 = unsafe { mem::zeroed() }; // undefined behavior! ⚠️ // The equivalent code with `MaybeUninit<&i32>`: let x: &i32 = unsafe { MaybeUninit::zeroed().assume_init() }; // undefined behavior! ⚠️ ``` This is exploited by the compiler for various optimizations, such as eliding run-time checks and optimizing `enum` layout. Similarly, entirely uninitialized memory may have any content, while a `bool` must always be `true` or `false`. Hence, creating an uninitialized `bool` is undefined behavior: ``` use std::mem::{self, MaybeUninit}; let b: bool = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️ // The equivalent code with `MaybeUninit<bool>`: let b: bool = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️ ``` Moreover, uninitialized memory is special in that it does not have a fixed value (“fixed” meaning “it won’t change without being written to”). Reading the same uninitialized byte multiple times can give different results. This makes it undefined behavior to have uninitialized data in a variable even if that variable has an integer type, which otherwise can hold any *fixed* bit pattern: ``` use std::mem::{self, MaybeUninit}; let x: i32 = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️ // The equivalent code with `MaybeUninit<i32>`: let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️ ``` On top of that, remember that most types have additional invariants beyond merely being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`](../vec/struct.vec) is considered initialized (under the current implementation; this does not constitute a stable guarantee) because the only requirement the compiler knows about it is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause *immediate* undefined behavior, but will cause undefined behavior with most safe operations (including dropping it). Examples -------- `MaybeUninit<T>` serves to enable unsafe code to deal with uninitialized data. It is a signal to the compiler indicating that the data here might *not* be initialized: ``` use std::mem::MaybeUninit; // Create an explicitly uninitialized reference. The compiler knows that data inside // a `MaybeUninit<T>` may be invalid, and hence this is not UB: let mut x = MaybeUninit::<&i32>::uninit(); // Set it to a valid value. x.write(&0); // Extract the initialized data -- this is only allowed *after* properly // initializing `x`! let x = unsafe { x.assume_init() }; ``` The compiler then knows to not make any incorrect assumptions or optimizations on this code. You can think of `MaybeUninit<T>` as being a bit like `Option<T>` but without any of the run-time tracking and without any of the safety checks. ### out-pointers You can use `MaybeUninit<T>` to implement “out-pointers”: instead of returning data from a function, pass it a pointer to some (uninitialized) memory to put the result into. This can be useful when it is important for the caller to control how the memory the result is stored in gets allocated, and you want to avoid unnecessary moves. ``` use std::mem::MaybeUninit; unsafe fn make_vec(out: *mut Vec<i32>) { // `write` does not drop the old contents, which is important. out.write(vec![1, 2, 3]); } let mut v = MaybeUninit::uninit(); unsafe { make_vec(v.as_mut_ptr()); } // Now we know `v` is initialized! This also makes sure the vector gets // properly dropped. let v = unsafe { v.assume_init() }; assert_eq!(&v, &[1, 2, 3]); ``` ### Initializing an array element-by-element `MaybeUninit<T>` can be used to initialize a large array element-by-element: ``` use std::mem::{self, MaybeUninit}; let data = { // Create an uninitialized array of `MaybeUninit`. The `assume_init` is // safe because the type we are claiming to have initialized here is a // bunch of `MaybeUninit`s, which do not require initialization. let mut data: [MaybeUninit<Vec<u32>>; 1000] = unsafe { MaybeUninit::uninit().assume_init() }; // Dropping a `MaybeUninit` does nothing, so if there is a panic during this loop, // we have a memory leak, but there is no memory safety issue. for elem in &mut data[..] { elem.write(vec![42]); } // Everything is initialized. Transmute the array to the // initialized type. unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) } }; assert_eq!(&data[0], &[42]); ``` You can also work with partially initialized arrays, which could be found in low-level datastructures. ``` use std::mem::MaybeUninit; use std::ptr; // Create an uninitialized array of `MaybeUninit`. The `assume_init` is // safe because the type we are claiming to have initialized here is a // bunch of `MaybeUninit`s, which do not require initialization. let mut data: [MaybeUninit<String>; 1000] = unsafe { MaybeUninit::uninit().assume_init() }; // Count the number of elements we have assigned. let mut data_len: usize = 0; for elem in &mut data[0..500] { elem.write(String::from("hello")); data_len += 1; } // For each item in the array, drop if we allocated it. for elem in &mut data[0..data_len] { unsafe { ptr::drop_in_place(elem.as_mut_ptr()); } } ``` ### Initializing a struct field-by-field You can use `MaybeUninit<T>`, and the [`std::ptr::addr_of_mut`](../ptr/macro.addr_of_mut) macro, to initialize structs field by field: ``` use std::mem::MaybeUninit; use std::ptr::addr_of_mut; #[derive(Debug, PartialEq)] pub struct Foo { name: String, list: Vec<u8>, } let foo = { let mut uninit: MaybeUninit<Foo> = MaybeUninit::uninit(); let ptr = uninit.as_mut_ptr(); // Initializing the `name` field // Using `write` instead of assignment via `=` to not call `drop` on the // old, uninitialized value. unsafe { addr_of_mut!((*ptr).name).write("Bob".to_string()); } // Initializing the `list` field // If there is a panic here, then the `String` in the `name` field leaks. unsafe { addr_of_mut!((*ptr).list).write(vec![0, 1, 2]); } // All the fields are initialized, so we call `assume_init` to get an initialized Foo. unsafe { uninit.assume_init() } }; assert_eq!( foo, Foo { name: "Bob".to_string(), list: vec![0, 1, 2] } ); ``` Layout ------ `MaybeUninit<T>` is guaranteed to have the same size, alignment, and ABI as `T`: ``` use std::mem::{MaybeUninit, size_of, align_of}; assert_eq!(size_of::<MaybeUninit<u64>>(), size_of::<u64>()); assert_eq!(align_of::<MaybeUninit<u64>>(), align_of::<u64>()); ``` However remember that a type *containing* a `MaybeUninit<T>` is not necessarily the same layout; Rust does not in general guarantee that the fields of a `Foo<T>` have the same order as a `Foo<U>` even if `T` and `U` have the same size and alignment. Furthermore because any bit value is valid for a `MaybeUninit<T>` the compiler can’t apply non-zero/niche-filling optimizations, potentially resulting in a larger size: ``` assert_eq!(size_of::<Option<bool>>(), 1); assert_eq!(size_of::<Option<MaybeUninit<bool>>>(), 2); ``` If `T` is FFI-safe, then so is `MaybeUninit<T>`. While `MaybeUninit` is `#[repr(transparent)]` (indicating it guarantees the same size, alignment, and ABI as `T`), this does *not* change any of the previous caveats. `Option<T>` and `Option<MaybeUninit<T>>` may still have different sizes, and types containing a field of type `T` may be laid out (and sized) differently than if that field were `MaybeUninit<T>`. `MaybeUninit` is a union type, and `#[repr(transparent)]` on unions is unstable (see [the tracking issue](https://github.com/rust-lang/rust/issues/60405)). Over time, the exact guarantees of `#[repr(transparent)]` on unions may evolve, and `MaybeUninit` may or may not remain `#[repr(transparent)]`. That said, `MaybeUninit<T>` will *always* guarantee that it has the same size, alignment, and ABI as `T`; it’s just that the way `MaybeUninit` implements that guarantee may evolve. Implementations --------------- [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#799)### impl<T, A> Box<MaybeUninit<T>, A>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#831)const: [unstable](https://github.com/rust-lang/rust/issues/92521 "Tracking issue for const_box") · #### pub unsafe fn assume\_init(self) -> Box<T, A> Notable traits for [Box](../boxed/struct.box "struct std::boxed::Box")<I, A> ``` impl<I, A> Iterator for Box<I, A>where     I: Iterator + ?Sized,     A: Allocator, type Item = <I as Iterator>::Item; impl<F, A> Future for Box<F, A>where     F: Future + Unpin + ?Sized,     A: Allocator + 'static, type Output = <F as Future>::Output; impl<R: Read + ?Sized> Read for Box<R> impl<W: Write + ?Sized> Write for Box<W> ``` 🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291)) Converts to `Box<T, A>`. ##### Safety As with [`MaybeUninit::assume_init`](union.maybeuninit#method.assume_init), it is up to the caller to guarantee that the value really is in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior. ##### Examples ``` #![feature(new_uninit)] let mut five = Box::<u32>::new_uninit(); let five: Box<u32> = unsafe { // Deferred initialization: five.as_mut_ptr().write(5); five.assume_init() }; assert_eq!(*five, 5) ``` [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#866)const: [unstable](https://github.com/rust-lang/rust/issues/92521 "Tracking issue for const_box") · #### pub fn write(boxed: Box<MaybeUninit<T>, A>, value: T) -> Box<T, A> Notable traits for [Box](../boxed/struct.box "struct std::boxed::Box")<I, A> ``` impl<I, A> Iterator for Box<I, A>where     I: Iterator + ?Sized,     A: Allocator, type Item = <I as Iterator>::Item; impl<F, A> Future for Box<F, A>where     F: Future + Unpin + ?Sized,     A: Allocator + 'static, type Output = <F as Future>::Output; impl<R: Read + ?Sized> Read for Box<R> impl<W: Write + ?Sized> Write for Box<W> ``` 🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291)) Writes the value and converts to `Box<T, A>`. This method converts the box similarly to [`Box::assume_init`](../boxed/struct.box#method.assume_init "Box::assume_init") but writes `value` into it before conversion thus guaranteeing safety. In some scenarios use of this method may improve performance because the compiler may be able to optimize copying from stack. ##### Examples ``` #![feature(new_uninit)] let big_box = Box::<[usize; 1024]>::new_uninit(); let mut array = [0; 1024]; for (i, place) in array.iter_mut().enumerate() { *place = i; } // The optimizer may be able to elide this copy, so previous code writes // to heap directly. let big_box = Box::write(big_box, array); for (i, x) in big_box.iter().enumerate() { assert_eq!(*x, i); } ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#271)### impl<T> MaybeUninit<T> [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#291)const: 1.36.0 · #### pub const fn new(val: T) -> MaybeUninit<T> Creates a new `MaybeUninit<T>` initialized with the given value. It is safe to call [`assume_init`](union.maybeuninit#method.assume_init) on the return value of this function. Note that dropping a `MaybeUninit<T>` will never call `T`’s drop code. It is your responsibility to make sure `T` gets dropped if it got initialized. ##### Example ``` use std::mem::MaybeUninit; let v: MaybeUninit<Vec<u8>> = MaybeUninit::new(vec![42]); ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#314)const: 1.36.0 · #### pub const fn uninit() -> MaybeUninit<T> Creates a new `MaybeUninit<T>` in an uninitialized state. Note that dropping a `MaybeUninit<T>` will never call `T`’s drop code. It is your responsibility to make sure `T` gets dropped if it got initialized. See the [type-level documentation](union.maybeuninit "MaybeUninit") for some examples. ##### Example ``` use std::mem::MaybeUninit; let v: MaybeUninit<String> = MaybeUninit::uninit(); ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#351)const: [unstable](https://github.com/rust-lang/rust/issues/96097 "Tracking issue for const_maybe_uninit_uninit_array") · #### pub fn uninit\_array<const N: usize>() -> [MaybeUninit<T>; N] 🔬This is a nightly-only experimental API. (`maybe_uninit_uninit_array` [#96097](https://github.com/rust-lang/rust/issues/96097)) Create a new array of `MaybeUninit<T>` items, in an uninitialized state. Note: in a future Rust version this method may become unnecessary when Rust allows [inline const expressions](https://github.com/rust-lang/rust/issues/76001). The example below could then use `let mut buf = [const { MaybeUninit::<u8>::uninit() }; 32];`. ##### Examples ``` #![feature(maybe_uninit_uninit_array, maybe_uninit_slice)] use std::mem::MaybeUninit; extern "C" { fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize; } /// Returns a (possibly smaller) slice of data that was actually read fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] { unsafe { let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len()); MaybeUninit::slice_assume_init_ref(&buf[..len]) } } let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array(); let data = read(&mut buf); ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#396)const: [unstable](https://github.com/rust-lang/rust/issues/91850 "Tracking issue for const_maybe_uninit_zeroed") · #### pub fn zeroed() -> MaybeUninit<T> Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being filled with `0` bytes. It depends on `T` whether that already makes for proper initialization. For example, `MaybeUninit<usize>::zeroed()` is initialized, but `MaybeUninit<&'static i32>::zeroed()` is not because references must not be null. Note that dropping a `MaybeUninit<T>` will never call `T`’s drop code. It is your responsibility to make sure `T` gets dropped if it got initialized. ##### Example Correct usage of this function: initializing a struct with zero, where all fields of the struct can hold the bit-pattern 0 as a valid value. ``` use std::mem::MaybeUninit; let x = MaybeUninit::<(u8, bool)>::zeroed(); let x = unsafe { x.assume_init() }; assert_eq!(x, (0, false)); ``` *Incorrect* usage of this function: calling `x.zeroed().assume_init()` when `0` is not a valid bit-pattern for the type: ``` use std::mem::MaybeUninit; enum NotZero { One = 1, Two = 2 } let x = MaybeUninit::<(u8, NotZero)>::zeroed(); let x = unsafe { x.assume_init() }; // Inside a pair, we create a `NotZero` that does not have a valid discriminant. // This is undefined behavior. ⚠️ ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#489)1.55.0 (const: [unstable](https://github.com/rust-lang/rust/issues/63567 "Tracking issue for const_maybe_uninit_write")) · #### pub fn write(&mut self, val: T) -> &mut T Sets the value of the `MaybeUninit<T>`. This overwrites any previous value without dropping it, so be careful not to use this twice unless you want to skip running the destructor. For your convenience, this also returns a mutable reference to the (now safely initialized) contents of `self`. As the content is stored inside a `MaybeUninit`, the destructor is not run for the inner data if the MaybeUninit leaves scope without a call to [`assume_init`](union.maybeuninit#method.assume_init), [`assume_init_drop`](union.maybeuninit#method.assume_init_drop), or similar. Code that receives the mutable reference returned by this function needs to keep this in mind. The safety model of Rust regards leaks as safe, but they are usually still undesirable. This being said, the mutable reference behaves like any other mutable reference would, so assigning a new value to it will drop the old content. ##### Examples Correct usage of this method: ``` use std::mem::MaybeUninit; let mut x = MaybeUninit::<Vec<u8>>::uninit(); { let hello = x.write((&b"Hello, world!").to_vec()); // Setting hello does not leak prior allocations, but drops them *hello = (&b"Hello").to_vec(); hello[0] = 'h' as u8; } // x is initialized now: let s = unsafe { x.assume_init() }; assert_eq!(b"hello", s.as_slice()); ``` This usage of the method causes a leak: ``` use std::mem::MaybeUninit; let mut x = MaybeUninit::<String>::uninit(); x.write("Hello".to_string()); // This leaks the contained string: x.write("hello".to_string()); // x is initialized now: let s = unsafe { x.assume_init() }; ``` This method can be used to avoid unsafe in some cases. The example below shows a part of an implementation of a fixed sized arena that lends out pinned references. With `write`, we can avoid the need to write through a raw pointer: ``` use core::pin::Pin; use core::mem::MaybeUninit; struct PinArena<T> { memory: Box<[MaybeUninit<T>]>, len: usize, } impl <T> PinArena<T> { pub fn capacity(&self) -> usize { self.memory.len() } pub fn push(&mut self, val: T) -> Pin<&mut T> { if self.len >= self.capacity() { panic!("Attempted to push to a full pin arena!"); } let ref_ = self.memory[self.len].write(val); self.len += 1; unsafe { Pin::new_unchecked(ref_) } } } ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#529)const: 1.59.0 · #### pub const fn as\_ptr(&self) -> \*const T Gets a pointer to the contained value. Reading from this pointer or turning it into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized. Writing to memory that this pointer (non-transitively) points to is undefined behavior (except inside an `UnsafeCell<T>`). ##### Examples Correct usage of this method: ``` use std::mem::MaybeUninit; let mut x = MaybeUninit::<Vec<u32>>::uninit(); x.write(vec![0, 1, 2]); // Create a reference into the `MaybeUninit<T>`. This is okay because we initialized it. let x_vec = unsafe { &*x.as_ptr() }; assert_eq!(x_vec.len(), 3); ``` *Incorrect* usage of this method: ``` use std::mem::MaybeUninit; let x = MaybeUninit::<Vec<u32>>::uninit(); let x_vec = unsafe { &*x.as_ptr() }; // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️ ``` (Notice that the rules around references to uninitialized data are not finalized yet, but until they are, it is advisable to avoid them.) [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#568)const: [unstable](https://github.com/rust-lang/rust/issues/75251 "Tracking issue for const_maybe_uninit_as_mut_ptr") · #### pub fn as\_mut\_ptr(&mut self) -> \*mut T Gets a mutable pointer to the contained value. Reading from this pointer or turning it into a reference is undefined behavior unless the `MaybeUninit<T>` is initialized. ##### Examples Correct usage of this method: ``` use std::mem::MaybeUninit; let mut x = MaybeUninit::<Vec<u32>>::uninit(); x.write(vec![0, 1, 2]); // Create a reference into the `MaybeUninit<Vec<u32>>`. // This is okay because we initialized it. let x_vec = unsafe { &mut *x.as_mut_ptr() }; x_vec.push(3); assert_eq!(x_vec.len(), 4); ``` *Incorrect* usage of this method: ``` use std::mem::MaybeUninit; let mut x = MaybeUninit::<Vec<u32>>::uninit(); let x_vec = unsafe { &mut *x.as_mut_ptr() }; // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️ ``` (Notice that the rules around references to uninitialized data are not finalized yet, but until they are, it is advisable to avoid them.) [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#623)const: 1.59.0 · #### pub const unsafe fn assume\_init(self) -> T Extracts the value from the `MaybeUninit<T>` container. This is a great way to ensure that the data will get dropped, because the resulting `T` is subject to the usual drop handling. ##### Safety It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior. The [type-level documentation](#initialization-invariant) contains more information about this initialization invariant. On top of that, remember that most types have additional invariants beyond merely being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`](../vec/struct.vec) is considered initialized (under the current implementation; this does not constitute a stable guarantee) because the only requirement the compiler knows about it is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause *immediate* undefined behavior, but will cause undefined behavior with most safe operations (including dropping it). ##### Examples Correct usage of this method: ``` use std::mem::MaybeUninit; let mut x = MaybeUninit::<bool>::uninit(); x.write(true); let x_init = unsafe { x.assume_init() }; assert_eq!(x_init, true); ``` *Incorrect* usage of this method: ``` use std::mem::MaybeUninit; let x = MaybeUninit::<Vec<u32>>::uninit(); let x_init = unsafe { x.assume_init() }; // `x` had not been initialized yet, so this last line caused undefined behavior. ⚠️ ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#693)1.60.0 (const: [unstable](https://github.com/rust-lang/rust/issues/63567 "Tracking issue for const_maybe_uninit_assume_init_read")) · #### pub unsafe fn assume\_init\_read(&self) -> T Reads the value from the `MaybeUninit<T>` container. The resulting `T` is subject to the usual drop handling. Whenever possible, it is preferable to use [`assume_init`](union.maybeuninit#method.assume_init) instead, which prevents duplicating the content of the `MaybeUninit<T>`. ##### Safety It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized state. Calling this when the content is not yet fully initialized causes undefined behavior. The [type-level documentation](#initialization-invariant) contains more information about this initialization invariant. Moreover, similar to the [`ptr::read`](../ptr/fn.read "ptr::read") function, this function creates a bitwise copy of the contents, regardless whether the contained type implements the [`Copy`](../marker/trait.copy "Copy") trait or not. When using multiple copies of the data (by calling `assume_init_read` multiple times, or first calling `assume_init_read` and then [`assume_init`](union.maybeuninit#method.assume_init)), it is your responsibility to ensure that that data may indeed be duplicated. ##### Examples Correct usage of this method: ``` use std::mem::MaybeUninit; let mut x = MaybeUninit::<u32>::uninit(); x.write(13); let x1 = unsafe { x.assume_init_read() }; // `u32` is `Copy`, so we may read multiple times. let x2 = unsafe { x.assume_init_read() }; assert_eq!(x1, x2); let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit(); x.write(None); let x1 = unsafe { x.assume_init_read() }; // Duplicating a `None` value is okay, so we may read multiple times. let x2 = unsafe { x.assume_init_read() }; assert_eq!(x1, x2); ``` *Incorrect* usage of this method: ``` use std::mem::MaybeUninit; let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit(); x.write(Some(vec![0, 1, 2])); let x1 = unsafe { x.assume_init_read() }; let x2 = unsafe { x.assume_init_read() }; // We now created two copies of the same vector, leading to a double-free ⚠️ when // they both get dropped! ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#725)1.60.0 · #### pub unsafe fn assume\_init\_drop(&mut self) Drops the contained value in place. If you have ownership of the `MaybeUninit`, you can also use [`assume_init`](union.maybeuninit#method.assume_init) as an alternative. ##### Safety It is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized state. Calling this when the content is not yet fully initialized causes undefined behavior. On top of that, all additional invariants of the type `T` must be satisfied, as the `Drop` implementation of `T` (or its members) may rely on this. For example, setting a [`Vec<T>`](../vec/struct.vec) to an invalid but non-null address makes it initialized (under the current implementation; this does not constitute a stable guarantee), because the only requirement the compiler knows about it is that the data pointer must be non-null. Dropping such a `Vec<T>` however will cause undefined behaviour. [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#787)1.55.0 (const: 1.59.0) · #### pub const unsafe fn assume\_init\_ref(&self) -> &T Gets a shared reference to the contained value. This can be useful when we want to access a `MaybeUninit` that has been initialized but don’t have ownership of the `MaybeUninit` (preventing the use of `.assume_init()`). ##### Safety Calling this when the content is not yet fully initialized causes undefined behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized state. ##### Examples ###### [Correct usage of this method:](#correct-usage-of-this-method) ``` use std::mem::MaybeUninit; let mut x = MaybeUninit::<Vec<u32>>::uninit(); // Initialize `x`: x.write(vec![1, 2, 3]); // Now that our `MaybeUninit<_>` is known to be initialized, it is okay to // create a shared reference to it: let x: &Vec<u32> = unsafe { // SAFETY: `x` has been initialized. x.assume_init_ref() }; assert_eq!(x, &vec![1, 2, 3]); ``` ###### [*Incorrect* usages of this method:](#incorrect-usages-of-this-method) ``` use std::mem::MaybeUninit; let x = MaybeUninit::<Vec<u32>>::uninit(); let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() }; // We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️ ``` ``` use std::{cell::Cell, mem::MaybeUninit}; let b = MaybeUninit::<Cell<bool>>::uninit(); // Initialize the `MaybeUninit` using `Cell::set`: unsafe { b.assume_init_ref().set(true); // ^^^^^^^^^^^^^^^ // Reference to an uninitialized `Cell<bool>`: UB! } ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#904)1.55.0 (const: unstable) · #### pub unsafe fn assume\_init\_mut(&mut self) -> &mut T Gets a mutable (unique) reference to the contained value. This can be useful when we want to access a `MaybeUninit` that has been initialized but don’t have ownership of the `MaybeUninit` (preventing the use of `.assume_init()`). ##### Safety Calling this when the content is not yet fully initialized causes undefined behavior: it is up to the caller to guarantee that the `MaybeUninit<T>` really is in an initialized state. For instance, `.assume_init_mut()` cannot be used to initialize a `MaybeUninit`. ##### Examples ###### [Correct usage of this method:](#correct-usage-of-this-method-1) ``` use std::mem::MaybeUninit; extern "C" { /// Initializes *all* the bytes of the input buffer. fn initialize_buffer(buf: *mut [u8; 1024]); } let mut buf = MaybeUninit::<[u8; 1024]>::uninit(); // Initialize `buf`: unsafe { initialize_buffer(buf.as_mut_ptr()); } // Now we know that `buf` has been initialized, so we could `.assume_init()` it. // However, using `.assume_init()` may trigger a `memcpy` of the 1024 bytes. // To assert our buffer has been initialized without copying it, we upgrade // the `&mut MaybeUninit<[u8; 1024]>` to a `&mut [u8; 1024]`: let buf: &mut [u8; 1024] = unsafe { // SAFETY: `buf` has been initialized. buf.assume_init_mut() }; // Now we can use `buf` as a normal slice: buf.sort_unstable(); assert!( buf.windows(2).all(|pair| pair[0] <= pair[1]), "buffer is sorted", ); ``` ###### [*Incorrect* usages of this method:](#incorrect-usages-of-this-method-1) You cannot use `.assume_init_mut()` to initialize a value: ``` use std::mem::MaybeUninit; let mut b = MaybeUninit::<bool>::uninit(); unsafe { *b.assume_init_mut() = true; // We have created a (mutable) reference to an uninitialized `bool`! // This is undefined behavior. ⚠️ } ``` For instance, you cannot [`Read`](../io/trait.read) into an uninitialized buffer: ``` use std::{io, mem::MaybeUninit}; fn read_chunk (reader: &'_ mut dyn io::Read) -> io::Result<[u8; 64]> { let mut buffer = MaybeUninit::<[u8; 64]>::uninit(); reader.read_exact(unsafe { buffer.assume_init_mut() })?; // ^^^^^^^^^^^^^^^^^^^^^^^^ // (mutable) reference to uninitialized memory! // This is undefined behavior. Ok(unsafe { buffer.assume_init() }) } ``` Nor can you use direct field access to do field-by-field gradual initialization: ``` use std::{mem::MaybeUninit, ptr}; struct Foo { a: u32, b: u8, } let foo: Foo = unsafe { let mut foo = MaybeUninit::<Foo>::uninit(); ptr::write(&mut foo.assume_init_mut().a as *mut u32, 1337); // ^^^^^^^^^^^^^^^^^^^^^ // (mutable) reference to uninitialized memory! // This is undefined behavior. ptr::write(&mut foo.assume_init_mut().b as *mut u8, 42); // ^^^^^^^^^^^^^^^^^^^^^ // (mutable) reference to uninitialized memory! // This is undefined behavior. foo.assume_init() }; ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#943)const: [unstable](https://github.com/rust-lang/rust/issues/96097 "Tracking issue for const_maybe_uninit_array_assume_init") · #### pub unsafe fn array\_assume\_init<const N: usize>( array: [MaybeUninit<T>; N]) -> [T; N] 🔬This is a nightly-only experimental API. (`maybe_uninit_array_assume_init` [#96097](https://github.com/rust-lang/rust/issues/96097)) Extracts the values from an array of `MaybeUninit` containers. ##### Safety It is up to the caller to guarantee that all elements of the array are in an initialized state. ##### Examples ``` #![feature(maybe_uninit_uninit_array)] #![feature(maybe_uninit_array_assume_init)] use std::mem::MaybeUninit; let mut array: [MaybeUninit<i32>; 3] = MaybeUninit::uninit_array(); array[0].write(0); array[1].write(1); array[2].write(2); // SAFETY: Now safe as we initialised all elements let array = unsafe { MaybeUninit::array_assume_init(array) }; assert_eq!(array, [0, 1, 2]); ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#973)const: [unstable](https://github.com/rust-lang/rust/issues/63569 "Tracking issue for maybe_uninit_slice") · #### pub unsafe fn slice\_assume\_init\_ref(slice: &[MaybeUninit<T>]) -> &[T] Notable traits for &[[u8](../primitive.u8)] ``` impl Read for &[u8] impl Write for &mut [u8] ``` 🔬This is a nightly-only experimental API. (`maybe_uninit_slice` [#63569](https://github.com/rust-lang/rust/issues/63569)) Assuming all the elements are initialized, get a slice to them. ##### Safety It is up to the caller to guarantee that the `MaybeUninit<T>` elements really are in an initialized state. Calling this when the content is not yet fully initialized causes undefined behavior. See [`assume_init_ref`](union.maybeuninit#method.assume_init_ref) for more details and examples. [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#995)const: unstable · #### pub unsafe fn slice\_assume\_init\_mut(slice: &mut [MaybeUninit<T>]) -> &mut [T] Notable traits for &[[u8](../primitive.u8)] ``` impl Read for &[u8] impl Write for &mut [u8] ``` 🔬This is a nightly-only experimental API. (`maybe_uninit_slice` [#63569](https://github.com/rust-lang/rust/issues/63569)) Assuming all the elements are initialized, get a mutable slice to them. ##### Safety It is up to the caller to guarantee that the `MaybeUninit<T>` elements really are in an initialized state. Calling this when the content is not yet fully initialized causes undefined behavior. See [`assume_init_mut`](union.maybeuninit#method.assume_init_mut) for more details and examples. [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#1005)const: [unstable](https://github.com/rust-lang/rust/issues/63569 "Tracking issue for maybe_uninit_slice") · #### pub fn slice\_as\_ptr(this: &[MaybeUninit<T>]) -> \*const T 🔬This is a nightly-only experimental API. (`maybe_uninit_slice` [#63569](https://github.com/rust-lang/rust/issues/63569)) Gets a pointer to the first element of the array. [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#1013)const: [unstable](https://github.com/rust-lang/rust/issues/63569 "Tracking issue for maybe_uninit_slice") · #### pub fn slice\_as\_mut\_ptr(this: &mut [MaybeUninit<T>]) -> \*mut T 🔬This is a nightly-only experimental API. (`maybe_uninit_slice` [#63569](https://github.com/rust-lang/rust/issues/63569)) Gets a mutable pointer to the first element of the array. [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#1061-1063)#### pub fn write\_slice(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T]where T: [Copy](../marker/trait.copy "trait std::marker::Copy"), Notable traits for &[[u8](../primitive.u8)] ``` impl Read for &[u8] impl Write for &mut [u8] ``` 🔬This is a nightly-only experimental API. (`maybe_uninit_write_slice` [#79995](https://github.com/rust-lang/rust/issues/79995)) Copies the elements from `src` to `this`, returning a mutable reference to the now initialized contents of `this`. If `T` does not implement `Copy`, use [`write_slice_cloned`](union.maybeuninit#method.write_slice_cloned) This is similar to [`slice::copy_from_slice`](../primitive.slice#method.copy_from_slice "slice::copy_from_slice"). ##### Panics This function will panic if the two slices have different lengths. ##### Examples ``` #![feature(maybe_uninit_write_slice)] use std::mem::MaybeUninit; let mut dst = [MaybeUninit::uninit(); 32]; let src = [0; 32]; let init = MaybeUninit::write_slice(&mut dst, &src); assert_eq!(init, src); ``` ``` #![feature(maybe_uninit_write_slice)] use std::mem::MaybeUninit; let mut vec = Vec::with_capacity(32); let src = [0; 16]; MaybeUninit::write_slice(&mut vec.spare_capacity_mut()[..src.len()], &src); // SAFETY: we have just copied all the elements of len into the spare capacity // the first src.len() elements of the vec are valid now. unsafe { vec.set_len(src.len()); } assert_eq!(vec, src); ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#1121-1123)#### pub fn write\_slice\_cloned( this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T]where T: [Clone](../clone/trait.clone "trait std::clone::Clone"), Notable traits for &[[u8](../primitive.u8)] ``` impl Read for &[u8] impl Write for &mut [u8] ``` 🔬This is a nightly-only experimental API. (`maybe_uninit_write_slice` [#79995](https://github.com/rust-lang/rust/issues/79995)) Clones the elements from `src` to `this`, returning a mutable reference to the now initialized contents of `this`. Any already initialized elements will not be dropped. If `T` implements `Copy`, use [`write_slice`](union.maybeuninit#method.write_slice) This is similar to [`slice::clone_from_slice`](../primitive.slice#method.clone_from_slice "slice::clone_from_slice") but does not drop existing elements. ##### Panics This function will panic if the two slices have different lengths, or if the implementation of `Clone` panics. If there is a panic, the already cloned elements will be dropped. ##### Examples ``` #![feature(maybe_uninit_write_slice)] use std::mem::MaybeUninit; let mut dst = [MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit(), MaybeUninit::uninit()]; let src = ["wibbly".to_string(), "wobbly".to_string(), "timey".to_string(), "wimey".to_string(), "stuff".to_string()]; let init = MaybeUninit::write_slice_cloned(&mut dst, &src); assert_eq!(init, src); ``` ``` #![feature(maybe_uninit_write_slice)] use std::mem::MaybeUninit; let mut vec = Vec::with_capacity(32); let src = ["rust", "is", "a", "pretty", "cool", "language"]; MaybeUninit::write_slice_cloned(&mut vec.spare_capacity_mut()[..src.len()], &src); // SAFETY: we have just cloned all the elements of len into the spare capacity // the first src.len() elements of the vec are valid now. unsafe { vec.set_len(src.len()); } assert_eq!(vec, src); ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#1183)#### pub fn as\_bytes(&self) -> &[MaybeUninit<u8>] 🔬This is a nightly-only experimental API. (`maybe_uninit_as_bytes` [#93092](https://github.com/rust-lang/rust/issues/93092)) Returns the contents of this `MaybeUninit` as a slice of potentially uninitialized bytes. Note that even if the contents of a `MaybeUninit` have been initialized, the value may still contain padding bytes which are left uninitialized. ##### Examples ``` #![feature(maybe_uninit_as_bytes, maybe_uninit_slice)] use std::mem::MaybeUninit; let val = 0x12345678i32; let uninit = MaybeUninit::new(val); let uninit_bytes = uninit.as_bytes(); let bytes = unsafe { MaybeUninit::slice_assume_init_ref(uninit_bytes) }; assert_eq!(bytes, val.to_ne_bytes()); ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#1214)#### pub fn as\_bytes\_mut(&mut self) -> &mut [MaybeUninit<u8>] 🔬This is a nightly-only experimental API. (`maybe_uninit_as_bytes` [#93092](https://github.com/rust-lang/rust/issues/93092)) Returns the contents of this `MaybeUninit` as a mutable slice of potentially uninitialized bytes. Note that even if the contents of a `MaybeUninit` have been initialized, the value may still contain padding bytes which are left uninitialized. ##### Examples ``` #![feature(maybe_uninit_as_bytes)] use std::mem::MaybeUninit; let val = 0x12345678i32; let mut uninit = MaybeUninit::new(val); let uninit_bytes = uninit.as_bytes_mut(); if cfg!(target_endian = "little") { uninit_bytes[0].write(0xcd); } else { uninit_bytes[3].write(0xcd); } let val2 = unsafe { uninit.assume_init() }; assert_eq!(val2, 0x123456cd); ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#1244)#### pub fn slice\_as\_bytes(this: &[MaybeUninit<T>]) -> &[MaybeUninit<u8>] 🔬This is a nightly-only experimental API. (`maybe_uninit_as_bytes` [#93092](https://github.com/rust-lang/rust/issues/93092)) Returns the contents of this slice of `MaybeUninit` as a slice of potentially uninitialized bytes. Note that even if the contents of a `MaybeUninit` have been initialized, the value may still contain padding bytes which are left uninitialized. ##### Examples ``` #![feature(maybe_uninit_as_bytes, maybe_uninit_write_slice, maybe_uninit_slice)] use std::mem::MaybeUninit; let uninit = [MaybeUninit::new(0x1234u16), MaybeUninit::new(0x5678u16)]; let uninit_bytes = MaybeUninit::slice_as_bytes(&uninit); let bytes = unsafe { MaybeUninit::slice_assume_init_ref(&uninit_bytes) }; let val1 = u16::from_ne_bytes(bytes[0..2].try_into().unwrap()); let val2 = u16::from_ne_bytes(bytes[2..4].try_into().unwrap()); assert_eq!(&[val1, val2], &[0x1234u16, 0x5678u16]); ``` [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#1277)#### pub fn slice\_as\_bytes\_mut(this: &mut [MaybeUninit<T>]) -> &mut [MaybeUninit<u8>] 🔬This is a nightly-only experimental API. (`maybe_uninit_as_bytes` [#93092](https://github.com/rust-lang/rust/issues/93092)) Returns the contents of this mutable slice of `MaybeUninit` as a mutable slice of potentially uninitialized bytes. Note that even if the contents of a `MaybeUninit` have been initialized, the value may still contain padding bytes which are left uninitialized. ##### Examples ``` #![feature(maybe_uninit_as_bytes, maybe_uninit_write_slice, maybe_uninit_slice)] use std::mem::MaybeUninit; let mut uninit = [MaybeUninit::<u16>::uninit(), MaybeUninit::<u16>::uninit()]; let uninit_bytes = MaybeUninit::slice_as_bytes_mut(&mut uninit); MaybeUninit::write_slice(uninit_bytes, &[0x12, 0x34, 0x56, 0x78]); let vals = unsafe { MaybeUninit::slice_assume_init_ref(&uninit) }; if cfg!(target_endian = "little") { assert_eq!(vals, &[0x3412u16, 0x7856u16]); } else { assert_eq!(vals, &[0x1234u16, 0x5678u16]); } ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#256)### impl<T> Clone for MaybeUninit<T>where T: [Copy](../marker/trait.copy "trait std::marker::Copy"), [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#258)#### fn clone(&self) -> MaybeUninit<T> Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#265)1.41.0 · ### impl<T> Debug for MaybeUninit<T> [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#266)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#248)### impl<T> Copy for MaybeUninit<T>where T: [Copy](../marker/trait.copy "trait std::marker::Copy"), Auto Trait Implementations -------------------------- ### impl<T> RefUnwindSafe for MaybeUninit<T>where T: [RefUnwindSafe](../panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe"), ### impl<T> Send for MaybeUninit<T>where T: [Send](../marker/trait.send "trait std::marker::Send"), ### impl<T> Sync for MaybeUninit<T>where T: [Sync](../marker/trait.sync "trait std::marker::Sync"), ### impl<T> Unpin for MaybeUninit<T>where T: [Unpin](../marker/trait.unpin "trait std::marker::Unpin"), ### impl<T> UnwindSafe for MaybeUninit<T>where T: [UnwindSafe](../panic/trait.unwindsafe "trait std::panic::UnwindSafe"), Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Function std::mem::min_align_of_val Function std::mem::min\_align\_of\_val ====================================== ``` pub fn min_align_of_val<T>(val: &T) -> usizewhere    T: ?Sized, ``` 👎Deprecated since 1.2.0: use `align_of_val` instead Returns the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface)-required minimum alignment of the type of the value that `val` points to in bytes. Every reference to a value of the type `T` must be a multiple of this number. Examples -------- ``` use std::mem; assert_eq!(4, mem::min_align_of_val(&5i32)); ``` rust Trait std::convert::TryFrom Trait std::convert::TryFrom =========================== ``` pub trait TryFrom<T> { type Error; fn try_from(value: T) -> Result<Self, Self::Error>; } ``` Simple and safe type conversions that may fail in a controlled way under some circumstances. It is the reciprocal of [`TryInto`](trait.tryinto "TryInto"). This is useful when you are doing a type conversion that may trivially succeed but may also need special handling. For example, there is no way to convert an [`i64`](../primitive.i64 "i64") into an [`i32`](../primitive.i32 "i32") using the [`From`](trait.from "From") trait, because an [`i64`](../primitive.i64 "i64") may contain a value that an [`i32`](../primitive.i32 "i32") cannot represent and so the conversion would lose data. This might be handled by truncating the [`i64`](../primitive.i64 "i64") to an [`i32`](../primitive.i32 "i32") (essentially giving the [`i64`](../primitive.i64 "i64")’s value modulo [`i32::MAX`](../primitive.i32#associatedconstant.MAX "i32::MAX")) or by simply returning [`i32::MAX`](../primitive.i32#associatedconstant.MAX "i32::MAX"), or by some other method. The [`From`](trait.from "From") trait is intended for perfect conversions, so the `TryFrom` trait informs the programmer when a type conversion could go bad and lets them decide how to handle it. Generic Implementations ----------------------- * `TryFrom<T> for U` implies [`TryInto`](trait.tryinto "TryInto")`<U> for T` * [`try_from`](trait.tryfrom#tymethod.try_from) is reflexive, which means that `TryFrom<T> for T` is implemented and cannot fail – the associated `Error` type for calling `T::try_from()` on a value of type `T` is [`Infallible`](enum.infallible "Infallible"). When the [`!`](../primitive.never "!") type is stabilized [`Infallible`](enum.infallible "Infallible") and [`!`](../primitive.never "!") will be equivalent. `TryFrom<T>` can be implemented as follows: ``` struct GreaterThanZero(i32); impl TryFrom<i32> for GreaterThanZero { type Error = &'static str; fn try_from(value: i32) -> Result<Self, Self::Error> { if value <= 0 { Err("GreaterThanZero only accepts value superior than zero!") } else { Ok(GreaterThanZero(value)) } } } ``` Examples -------- As described, [`i32`](../primitive.i32 "i32") implements `TryFrom<`[`i64`](../primitive.i64 "i64")`>`: ``` let big_number = 1_000_000_000_000i64; // Silently truncates `big_number`, requires detecting // and handling the truncation after the fact. let smaller_number = big_number as i32; assert_eq!(smaller_number, -727379968); // Returns an error because `big_number` is too big to // fit in an `i32`. let try_smaller_number = i32::try_from(big_number); assert!(try_smaller_number.is_err()); // Returns `Ok(3)`. let try_successful_smaller_number = i32::try_from(3); assert!(try_successful_smaller_number.is_ok()); ``` Required Associated Types ------------------------- [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#474)#### type Error The type returned in the event of a conversion error. Required Methods ---------------- [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#478)#### fn try\_from(value: T) -> Result<Self, Self::Error> Performs the conversion. Implementors ------------ [source](https://doc.rust-lang.org/src/core/char/convert.rs.html#98)1.59.0 · ### impl TryFrom<char> for u8 Map `char` with code point in U+0000..=U+00FF to byte in 0x00..=0xFF with same value, failing if the code point is greater than U+00FF. See [`impl From<u8> for char`](../primitive.char#impl-From%3Cu8%3E-for-char) for details on the encoding. #### type Error = TryFromCharError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#286)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i8> for u8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#286)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i8> for u16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#286)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i8> for u32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#286)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i8> for u64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#286)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i8> for u128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#366)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i8> for usize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#493)1.46.0 · ### impl TryFrom<i8> for NonZeroI8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#273)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i16> for i8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#291)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i16> for u8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#287)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i16> for u16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#287)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i16> for u32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#287)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i16> for u64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#287)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i16> for u128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#366)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i16> for usize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#494)1.46.0 · ### impl TryFrom<i16> for NonZeroI16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#274)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i32> for i8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#274)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i32> for i16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#371)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i32> for isize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#292)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i32> for u8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#292)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i32> for u16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#288)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i32> for u32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#288)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i32> for u64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#288)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i32> for u128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#366)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i32> for usize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#495)1.46.0 · ### impl TryFrom<i32> for NonZeroI32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#275)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i64> for i8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#275)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i64> for i16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#275)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i64> for i32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#371)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i64> for isize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#293)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i64> for u8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#293)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i64> for u16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#293)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i64> for u32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#289)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i64> for u64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#289)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i64> for u128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#366)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i64> for usize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#496)1.46.0 · ### impl TryFrom<i64> for NonZeroI64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#276)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i128> for i8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#276)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i128> for i16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#276)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i128> for i32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#276)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i128> for i64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#372)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i128> for isize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#294)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i128> for u8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#294)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i128> for u16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#294)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i128> for u32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#294)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i128> for u64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#290)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i128> for u128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#367)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<i128> for usize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#497)1.46.0 · ### impl TryFrom<i128> for NonZeroI128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#361)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<isize> for i8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#361)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<isize> for i16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#361)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<isize> for i32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#362)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<isize> for i64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#362)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<isize> for i128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#359)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<isize> for u8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#359)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<isize> for u16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#359)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<isize> for u32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#360)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<isize> for u64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#360)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<isize> for u128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#298)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<isize> for usize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#498)1.46.0 · ### impl TryFrom<isize> for NonZeroIsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#279)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u8> for i8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#487)1.46.0 · ### impl TryFrom<u8> for NonZeroU8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#280)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u16> for i8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#280)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u16> for i16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#369)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u16> for isize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#268)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u16> for u8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#488)1.46.0 · ### impl TryFrom<u16> for NonZeroU16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/char/convert.rs.html#221)### impl TryFrom<u32> for char #### type Error = CharTryFromError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#281)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u32> for i8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#281)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u32> for i16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#281)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u32> for i32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#369)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u32> for isize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#269)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u32> for u8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#269)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u32> for u16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#364)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u32> for usize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#489)1.46.0 · ### impl TryFrom<u32> for NonZeroU32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#282)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u64> for i8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#282)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u64> for i16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#282)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u64> for i32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#282)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u64> for i64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#370)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u64> for isize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#270)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u64> for u8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#270)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u64> for u16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#270)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u64> for u32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#364)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u64> for usize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#490)1.46.0 · ### impl TryFrom<u64> for NonZeroU64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#283)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u128> for i8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#283)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u128> for i16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#283)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u128> for i32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#283)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u128> for i64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#283)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u128> for i128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#370)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u128> for isize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u128> for u8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u128> for u16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u128> for u32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u128> for u64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#365)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<u128> for usize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#491)1.46.0 · ### impl TryFrom<u128> for NonZeroU128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#356)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<usize> for i8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#356)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<usize> for i16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#356)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<usize> for i32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#356)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<usize> for i64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#357)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<usize> for i128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#297)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<usize> for isize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#354)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<usize> for u8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#354)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<usize> for u16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#354)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<usize> for u32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#355)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<usize> for u64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#355)const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num") · ### impl TryFrom<usize> for u128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#492)1.46.0 · ### impl TryFrom<usize> for NonZeroUsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#533)1.49.0 · ### impl TryFrom<NonZeroI8> for NonZeroU8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#534)1.49.0 · ### impl TryFrom<NonZeroI8> for NonZeroU16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#535)1.49.0 · ### impl TryFrom<NonZeroI8> for NonZeroU32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#536)1.49.0 · ### impl TryFrom<NonZeroI8> for NonZeroU64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#537)1.49.0 · ### impl TryFrom<NonZeroI8> for NonZeroU128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#538)1.49.0 · ### impl TryFrom<NonZeroI8> for NonZeroUsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#541)1.49.0 · ### impl TryFrom<NonZeroI16> for NonZeroI8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#533)1.49.0 · ### impl TryFrom<NonZeroI16> for NonZeroU8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#534)1.49.0 · ### impl TryFrom<NonZeroI16> for NonZeroU16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#535)1.49.0 · ### impl TryFrom<NonZeroI16> for NonZeroU32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#536)1.49.0 · ### impl TryFrom<NonZeroI16> for NonZeroU64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#537)1.49.0 · ### impl TryFrom<NonZeroI16> for NonZeroU128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#538)1.49.0 · ### impl TryFrom<NonZeroI16> for NonZeroUsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#541)1.49.0 · ### impl TryFrom<NonZeroI32> for NonZeroI8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#542)1.49.0 · ### impl TryFrom<NonZeroI32> for NonZeroI16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#546)1.49.0 · ### impl TryFrom<NonZeroI32> for NonZeroIsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#533)1.49.0 · ### impl TryFrom<NonZeroI32> for NonZeroU8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#534)1.49.0 · ### impl TryFrom<NonZeroI32> for NonZeroU16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#535)1.49.0 · ### impl TryFrom<NonZeroI32> for NonZeroU32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#536)1.49.0 · ### impl TryFrom<NonZeroI32> for NonZeroU64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#537)1.49.0 · ### impl TryFrom<NonZeroI32> for NonZeroU128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#538)1.49.0 · ### impl TryFrom<NonZeroI32> for NonZeroUsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#541)1.49.0 · ### impl TryFrom<NonZeroI64> for NonZeroI8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#542)1.49.0 · ### impl TryFrom<NonZeroI64> for NonZeroI16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#543)1.49.0 · ### impl TryFrom<NonZeroI64> for NonZeroI32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#546)1.49.0 · ### impl TryFrom<NonZeroI64> for NonZeroIsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#533)1.49.0 · ### impl TryFrom<NonZeroI64> for NonZeroU8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#534)1.49.0 · ### impl TryFrom<NonZeroI64> for NonZeroU16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#535)1.49.0 · ### impl TryFrom<NonZeroI64> for NonZeroU32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#536)1.49.0 · ### impl TryFrom<NonZeroI64> for NonZeroU64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#537)1.49.0 · ### impl TryFrom<NonZeroI64> for NonZeroU128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#538)1.49.0 · ### impl TryFrom<NonZeroI64> for NonZeroUsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#541)1.49.0 · ### impl TryFrom<NonZeroI128> for NonZeroI8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#542)1.49.0 · ### impl TryFrom<NonZeroI128> for NonZeroI16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#543)1.49.0 · ### impl TryFrom<NonZeroI128> for NonZeroI32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#544)1.49.0 · ### impl TryFrom<NonZeroI128> for NonZeroI64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#546)1.49.0 · ### impl TryFrom<NonZeroI128> for NonZeroIsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#533)1.49.0 · ### impl TryFrom<NonZeroI128> for NonZeroU8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#534)1.49.0 · ### impl TryFrom<NonZeroI128> for NonZeroU16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#535)1.49.0 · ### impl TryFrom<NonZeroI128> for NonZeroU32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#536)1.49.0 · ### impl TryFrom<NonZeroI128> for NonZeroU64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#537)1.49.0 · ### impl TryFrom<NonZeroI128> for NonZeroU128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#538)1.49.0 · ### impl TryFrom<NonZeroI128> for NonZeroUsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#541)1.49.0 · ### impl TryFrom<NonZeroIsize> for NonZeroI8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#542)1.49.0 · ### impl TryFrom<NonZeroIsize> for NonZeroI16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#543)1.49.0 · ### impl TryFrom<NonZeroIsize> for NonZeroI32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#544)1.49.0 · ### impl TryFrom<NonZeroIsize> for NonZeroI64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#545)1.49.0 · ### impl TryFrom<NonZeroIsize> for NonZeroI128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#533)1.49.0 · ### impl TryFrom<NonZeroIsize> for NonZeroU8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#534)1.49.0 · ### impl TryFrom<NonZeroIsize> for NonZeroU16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#535)1.49.0 · ### impl TryFrom<NonZeroIsize> for NonZeroU32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#536)1.49.0 · ### impl TryFrom<NonZeroIsize> for NonZeroU64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#537)1.49.0 · ### impl TryFrom<NonZeroIsize> for NonZeroU128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#538)1.49.0 · ### impl TryFrom<NonZeroIsize> for NonZeroUsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#541)1.49.0 · ### impl TryFrom<NonZeroU8> for NonZeroI8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#541)1.49.0 · ### impl TryFrom<NonZeroU16> for NonZeroI8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#542)1.49.0 · ### impl TryFrom<NonZeroU16> for NonZeroI16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#546)1.49.0 · ### impl TryFrom<NonZeroU16> for NonZeroIsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#533)1.49.0 · ### impl TryFrom<NonZeroU16> for NonZeroU8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#541)1.49.0 · ### impl TryFrom<NonZeroU32> for NonZeroI8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#542)1.49.0 · ### impl TryFrom<NonZeroU32> for NonZeroI16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#543)1.49.0 · ### impl TryFrom<NonZeroU32> for NonZeroI32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#546)1.49.0 · ### impl TryFrom<NonZeroU32> for NonZeroIsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#533)1.49.0 · ### impl TryFrom<NonZeroU32> for NonZeroU8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#534)1.49.0 · ### impl TryFrom<NonZeroU32> for NonZeroU16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#538)1.49.0 · ### impl TryFrom<NonZeroU32> for NonZeroUsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#541)1.49.0 · ### impl TryFrom<NonZeroU64> for NonZeroI8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#542)1.49.0 · ### impl TryFrom<NonZeroU64> for NonZeroI16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#543)1.49.0 · ### impl TryFrom<NonZeroU64> for NonZeroI32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#544)1.49.0 · ### impl TryFrom<NonZeroU64> for NonZeroI64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#546)1.49.0 · ### impl TryFrom<NonZeroU64> for NonZeroIsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#533)1.49.0 · ### impl TryFrom<NonZeroU64> for NonZeroU8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#534)1.49.0 · ### impl TryFrom<NonZeroU64> for NonZeroU16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#535)1.49.0 · ### impl TryFrom<NonZeroU64> for NonZeroU32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#538)1.49.0 · ### impl TryFrom<NonZeroU64> for NonZeroUsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#541)1.49.0 · ### impl TryFrom<NonZeroU128> for NonZeroI8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#542)1.49.0 · ### impl TryFrom<NonZeroU128> for NonZeroI16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#543)1.49.0 · ### impl TryFrom<NonZeroU128> for NonZeroI32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#544)1.49.0 · ### impl TryFrom<NonZeroU128> for NonZeroI64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#545)1.49.0 · ### impl TryFrom<NonZeroU128> for NonZeroI128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#546)1.49.0 · ### impl TryFrom<NonZeroU128> for NonZeroIsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#533)1.49.0 · ### impl TryFrom<NonZeroU128> for NonZeroU8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#534)1.49.0 · ### impl TryFrom<NonZeroU128> for NonZeroU16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#535)1.49.0 · ### impl TryFrom<NonZeroU128> for NonZeroU32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#536)1.49.0 · ### impl TryFrom<NonZeroU128> for NonZeroU64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#538)1.49.0 · ### impl TryFrom<NonZeroU128> for NonZeroUsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#541)1.49.0 · ### impl TryFrom<NonZeroUsize> for NonZeroI8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#542)1.49.0 · ### impl TryFrom<NonZeroUsize> for NonZeroI16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#543)1.49.0 · ### impl TryFrom<NonZeroUsize> for NonZeroI32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#544)1.49.0 · ### impl TryFrom<NonZeroUsize> for NonZeroI64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#545)1.49.0 · ### impl TryFrom<NonZeroUsize> for NonZeroI128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#546)1.49.0 · ### impl TryFrom<NonZeroUsize> for NonZeroIsize #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#533)1.49.0 · ### impl TryFrom<NonZeroUsize> for NonZeroU8 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#534)1.49.0 · ### impl TryFrom<NonZeroUsize> for NonZeroU16 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#535)1.49.0 · ### impl TryFrom<NonZeroUsize> for NonZeroU32 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#536)1.49.0 · ### impl TryFrom<NonZeroUsize> for NonZeroU64 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#537)1.49.0 · ### impl TryFrom<NonZeroUsize> for NonZeroU128 #### type Error = TryFromIntError [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#230-246)1.63.0 · ### impl TryFrom<HandleOrInvalid> for OwnedHandle Available on **Windows** only.#### type Error = InvalidHandleError [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#161-177)1.63.0 · ### impl TryFrom<HandleOrNull> for OwnedHandle Available on **Windows** only.#### type Error = NullHandleError [source](https://doc.rust-lang.org/src/core/array/mod.rs.html#212)### impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] #### type Error = TryFromSliceError [source](https://doc.rust-lang.org/src/core/array/mod.rs.html#227)### impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] #### type Error = TryFromSliceError [source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3115)1.48.0 · ### impl<T, A, const N: usize> TryFrom<Vec<T, A>> for [T; N]where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), #### type Error = Vec<T, A> [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · ### impl<T, U> TryFrom<U> for Twhere U: [Into](trait.into "trait std::convert::Into")<T>, #### type Error = Infallible [source](https://doc.rust-lang.org/src/core/array/mod.rs.html#188)### impl<T, const N: usize> TryFrom<&[T]> for [T; N]where T: [Copy](../marker/trait.copy "trait std::marker::Copy"), #### type Error = TryFromSliceError [source](https://doc.rust-lang.org/src/core/array/mod.rs.html#200)1.59.0 · ### impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]where T: [Copy](../marker/trait.copy "trait std::marker::Copy"), #### type Error = TryFromSliceError [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1626)1.43.0 · ### impl<T, const N: usize> TryFrom<Box<[T], Global>> for Box<[T; N], Global> #### type Error = Box<[T], Global> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2027)1.43.0 · ### impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]> #### type Error = Rc<[T]> [source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2631)1.43.0 · ### impl<T, const N: usize> TryFrom<Arc<[T]>> for Arc<[T; N]> #### type Error = Arc<[T]>
programming_docs
rust Trait std::convert::TryInto Trait std::convert::TryInto =========================== ``` pub trait TryInto<T> { type Error; fn try_into(self) -> Result<T, Self::Error>; } ``` An attempted conversion that consumes `self`, which may or may not be expensive. Library authors should usually not directly implement this trait, but should prefer implementing the [`TryFrom`](trait.tryfrom "TryFrom") trait, which offers greater flexibility and provides an equivalent `TryInto` implementation for free, thanks to a blanket implementation in the standard library. For more information on this, see the documentation for [`Into`](trait.into "Into"). Implementing `TryInto` ---------------------- This suffers the same restrictions and reasoning as implementing [`Into`](trait.into "Into"), see there for details. Required Associated Types ------------------------- [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#398)#### type Error The type returned in the event of a conversion error. Required Methods ---------------- [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#402)#### fn try\_into(self) -> Result<T, Self::Error> Performs the conversion. Implementors ------------ [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · ### impl<T, U> TryInto<U> for Twhere U: [TryFrom](trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error rust Module std::convert Module std::convert =================== Traits for conversions between types. The traits in this module provide a way to convert from one type to another type. Each trait serves a different purpose: * Implement the [`AsRef`](trait.asref "AsRef") trait for cheap reference-to-reference conversions * Implement the [`AsMut`](trait.asmut "AsMut") trait for cheap mutable-to-mutable conversions * Implement the [`From`](trait.from "From") trait for consuming value-to-value conversions * Implement the [`Into`](trait.into "Into") trait for consuming value-to-value conversions to types outside the current crate * The [`TryFrom`](trait.tryfrom "TryFrom") and [`TryInto`](trait.tryinto "TryInto") traits behave like [`From`](trait.from "From") and [`Into`](trait.into "Into"), but should be implemented when the conversion can fail. The traits in this module are often used as trait bounds for generic functions such that to arguments of multiple types are supported. See the documentation of each trait for examples. As a library author, you should always prefer implementing [`From<T>`](trait.from "From") or [`TryFrom<T>`](trait.tryfrom "TryFrom") rather than [`Into<U>`](trait.into "Into") or [`TryInto<U>`](trait.tryinto "TryInto"), as [`From`](trait.from "From") and [`TryFrom`](trait.tryfrom "TryFrom") provide greater flexibility and offer equivalent [`Into`](trait.into "Into") or [`TryInto`](trait.tryinto "TryInto") implementations for free, thanks to a blanket implementation in the standard library. When targeting a version prior to Rust 1.41, it may be necessary to implement [`Into`](trait.into "Into") or [`TryInto`](trait.tryinto "TryInto") directly when converting to a type outside the current crate. Generic Implementations ----------------------- * [`AsRef`](trait.asref "AsRef") and [`AsMut`](trait.asmut "AsMut") auto-dereference if the inner type is a reference * [`From`](trait.from "From")`<U> for T` implies [`Into`](trait.into "Into")`<T> for U` * [`TryFrom`](trait.tryfrom "TryFrom")`<U> for T` implies [`TryInto`](trait.tryinto "TryInto")`<T> for U` * [`From`](trait.from "From") and [`Into`](trait.into "Into") are reflexive, which means that all types can `into` themselves and `from` themselves See each trait for usage examples. Enums ----- [Infallible](enum.infallible "std::convert::Infallible enum") The error type for errors that can never happen. Traits ------ [FloatToInt](trait.floattoint "std::convert::FloatToInt trait")Experimental Supporting trait for inherent methods of `f32` and `f64` such as `to_int_unchecked`. Typically doesn’t need to be used directly. [AsMut](trait.asmut "std::convert::AsMut trait") Used to do a cheap mutable-to-mutable reference conversion. [AsRef](trait.asref "std::convert::AsRef trait") Used to do a cheap reference-to-reference conversion. [From](trait.from "std::convert::From trait") Used to do value-to-value conversions while consuming the input value. It is the reciprocal of [`Into`](trait.into "Into"). [Into](trait.into "std::convert::Into trait") A value-to-value conversion that consumes the input value. The opposite of [`From`](trait.from "From"). [TryFrom](trait.tryfrom "std::convert::TryFrom trait") Simple and safe type conversions that may fail in a controlled way under some circumstances. It is the reciprocal of [`TryInto`](trait.tryinto "TryInto"). [TryInto](trait.tryinto "std::convert::TryInto trait") An attempted conversion that consumes `self`, which may or may not be expensive. Functions --------- [identity](fn.identity "std::convert::identity fn") The identity function. rust Function std::convert::identity Function std::convert::identity =============================== ``` pub const fn identity<T>(x: T) -> T ``` The identity function. Two things are important to note about this function: * It is not always equivalent to a closure like `|x| x`, since the closure may coerce `x` into a different type. * It moves the input `x` passed to the function. While it might seem strange to have a function that just returns back the input, there are some interesting uses. Examples -------- Using `identity` to do nothing in a sequence of other, interesting, functions: ``` use std::convert::identity; fn manipulation(x: u32) -> u32 { // Let's pretend that adding one is an interesting function. x + 1 } let _arr = &[identity, manipulation]; ``` Using `identity` as a “do nothing” base case in a conditional: ``` use std::convert::identity; let do_stuff = if condition { manipulation } else { identity }; // Do more interesting stuff... let _results = do_stuff(42); ``` Using `identity` to keep the `Some` variants of an iterator of `Option<T>`: ``` use std::convert::identity; let iter = [Some(1), None, Some(3)].into_iter(); let filtered = iter.filter_map(identity).collect::<Vec<_>>(); assert_eq!(vec![1, 3], filtered); ``` rust Enum std::convert::Infallible Enum std::convert::Infallible ============================= ``` pub enum Infallible {} ``` The error type for errors that can never happen. Since this enum has no variant, a value of this type can never actually exist. This can be useful for generic APIs that use [`Result`](../result/enum.result "Result") and parameterize the error type, to indicate that the result is always [`Ok`](../result/enum.result#variant.Ok "Ok"). For example, the [`TryFrom`](trait.tryfrom "TryFrom") trait (conversion that returns a [`Result`](../result/enum.result "Result")) has a blanket implementation for all types where a reverse [`Into`](trait.into "Into") implementation exists. ⓘ ``` impl<T, U> TryFrom<U> for T where U: Into<T> { type Error = Infallible; fn try_from(value: U) -> Result<Self, Infallible> { Ok(U::into(value)) // Never returns `Err` } } ``` Future compatibility -------------------- This enum has the same role as [the `!` “never” type](../primitive.never "never"), which is unstable in this version of Rust. When `!` is stabilized, we plan to make `Infallible` a type alias to it: ⓘ ``` pub type Infallible = !; ``` … and eventually deprecate `Infallible`. However there is one case where `!` syntax can be used before `!` is stabilized as a full-fledged type: in the position of a function’s return type. Specifically, it is possible to have implementations for two different function pointer types: ``` trait MyTrait {} impl MyTrait for fn() -> ! {} impl MyTrait for fn() -> std::convert::Infallible {} ``` With `Infallible` being an enum, this code is valid. However when `Infallible` becomes an alias for the never type, the two `impl`s will start to overlap and therefore will be disallowed by the language’s trait coherence rules. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#701)const: [unstable](https://github.com/rust-lang/rust/issues/91805 "Tracking issue for const_clone") · ### impl Clone for Infallible [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#702)const: [unstable](https://github.com/rust-lang/rust/issues/91805 "Tracking issue for const_clone") · #### fn clone(&self) -> Infallible Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#708)### impl Debug for Infallible [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#709)#### fn fmt(&self, &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#715)### impl Display for Infallible [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)#### fn fmt(&self, &mut Formatter<'\_>) -> Result<(), Error> Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)1.8.0 · ### impl Error for Infallible [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#724)#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to\_string() [Read more](../error/trait.error#method.description) [source](https://doc.rust-lang.org/src/core/error.rs.html#83)1.30.0 · #### fn source(&self) -> Option<&(dyn Error + 'static)> The lower-level source of this error, if any. [Read more](../error/trait.error#method.source) [source](https://doc.rust-lang.org/src/core/error.rs.html#119)1.0.0 · #### fn cause(&self) -> Option<&dyn Error> 👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting [source](https://doc.rust-lang.org/src/core/error.rs.html#193)#### fn provide(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301)) Provides type based access to context intended for error reports. [Read more](../error/trait.error#method.provide) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · ### impl From<!> for Infallible [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#756)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(x: !) -> Infallible Converts to this type from the input type. [source](https://doc.rust-lang.org/src/core/num/error.rs.html#35)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · ### impl From<Infallible> for TryFromIntError [source](https://doc.rust-lang.org/src/core/num/error.rs.html#36)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(x: Infallible) -> TryFromIntError Converts to this type from the input type. [source](https://doc.rust-lang.org/src/core/array/mod.rs.html#149)1.36.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl From<Infallible> for TryFromSliceError [source](https://doc.rust-lang.org/src/core/array/mod.rs.html#150)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(x: Infallible) -> TryFromSliceError Converts to this type from the input type. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#762)1.44.0 · ### impl Hash for Infallible [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)#### fn hash<H>(&self, &mut H)where H: [Hasher](../hash/trait.hasher "trait std::hash::Hasher"), Feeds this value into the given [`Hasher`](../hash/trait.hasher "Hasher"). [Read more](../hash/trait.hash#tymethod.hash) [source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0 · #### fn hash\_slice<H>(data: &[Self], state: &mut H)where H: [Hasher](../hash/trait.hasher "trait std::hash::Hasher"), Feeds a slice of this type into the given [`Hasher`](../hash/trait.hasher "Hasher"). [Read more](../hash/trait.hash#method.hash_slice) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#747)### impl Ord for Infallible [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)#### fn cmp(&self, \_other: &Infallible) -> Ordering This method returns an [`Ordering`](../cmp/enum.ordering "Ordering") between `self` and `other`. [Read more](../cmp/trait.ord#tymethod.cmp) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#804-807)1.21.0 · #### fn max(self, other: Self) -> Self Compares and returns the maximum of two values. [Read more](../cmp/trait.ord#method.max) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#831-834)1.21.0 · #### fn min(self, other: Self) -> Self Compares and returns the minimum of two values. [Read more](../cmp/trait.ord#method.min) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#863-867)1.50.0 · #### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<Self>, Restrict a value to a certain interval. [Read more](../cmp/trait.ord#method.clamp) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#730)### impl PartialEq<Infallible> for Infallible [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#731)#### fn eq(&self, &Infallible) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)1.0.0 · #### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#740)### impl PartialOrd<Infallible> for Infallible [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#741)#### fn partial\_cmp(&self, \_other: &Infallible) -> Option<Ordering> This method returns an ordering between `self` and `other` values if one exists. [Read more](../cmp/trait.partialord#tymethod.partial_cmp) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1138)1.0.0 · #### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](../cmp/trait.partialord#method.lt) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1157)1.0.0 · #### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](../cmp/trait.partialord#method.le) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1175)1.0.0 · #### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](../cmp/trait.partialord#method.gt) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#1194)1.0.0 · #### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](../cmp/trait.partialord#method.ge) [source](https://doc.rust-lang.org/src/std/process.rs.html#2183-2187)1.61.0 · ### impl Termination for Infallible [source](https://doc.rust-lang.org/src/std/process.rs.html#2184-2186)#### fn report(self) -> ExitCode Is called to get the representation of the value as status code. This status code is returned to the operating system. [Read more](../process/trait.termination#tymethod.report) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#696)### impl Copy for Infallible [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#737)### impl Eq for Infallible Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for Infallible ### impl Send for Infallible ### impl Sync for Infallible ### impl Unpin for Infallible ### impl UnwindSafe for Infallible Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#577)### impl<T> From<!> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#578)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: !) -> T Converts to this type from the input type. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/error.rs.html#197)### impl<E> Provider for Ewhere E: [Error](../error/trait.error "trait std::error::Error") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/error.rs.html#201)#### fn provide(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`provide_any` [#96024](https://github.com/rust-lang/rust/issues/96024)) Data providers should implement this method to provide *all* values they are able to provide by using `demand`. [Read more](../any/trait.provider#tymethod.provide) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2500)### impl<T> ToString for Twhere T: [Display](../fmt/trait.display "trait std::fmt::Display") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2506)#### default fn to\_string(&self) -> String Converts the given value to a `String`. [Read more](../string/trait.tostring#tymethod.to_string) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Trait std::convert::Into Trait std::convert::Into ======================== ``` pub trait Into<T> { fn into(self) -> T; } ``` A value-to-value conversion that consumes the input value. The opposite of [`From`](trait.from "From"). One should avoid implementing [`Into`](trait.into "Into") and implement [`From`](trait.from "From") instead. Implementing [`From`](trait.from "From") automatically provides one with an implementation of [`Into`](trait.into "Into") thanks to the blanket implementation in the standard library. Prefer using [`Into`](trait.into "Into") over [`From`](trait.from "From") when specifying trait bounds on a generic function to ensure that types that only implement [`Into`](trait.into "Into") can be used as well. **Note: This trait must not fail**. If the conversion can fail, use [`TryInto`](trait.tryinto "TryInto"). Generic Implementations ----------------------- * [`From`](trait.from "From")`<T> for U` implies `Into<U> for T` * [`Into`](trait.into "Into") is reflexive, which means that `Into<T> for T` is implemented Implementing `Into` for conversions to external types in old versions of Rust ----------------------------------------------------------------------------- Prior to Rust 1.41, if the destination type was not part of the current crate then you couldn’t implement [`From`](trait.from "From") directly. For example, take this code: ``` struct Wrapper<T>(Vec<T>); impl<T> From<Wrapper<T>> for Vec<T> { fn from(w: Wrapper<T>) -> Vec<T> { w.0 } } ``` This will fail to compile in older versions of the language because Rust’s orphaning rules used to be a little bit more strict. To bypass this, you could implement [`Into`](trait.into "Into") directly: ``` struct Wrapper<T>(Vec<T>); impl<T> Into<Vec<T>> for Wrapper<T> { fn into(self) -> Vec<T> { self.0 } } ``` It is important to understand that [`Into`](trait.into "Into") does not provide a [`From`](trait.from "From") implementation (as [`From`](trait.from "From") does with [`Into`](trait.into "Into")). Therefore, you should always try to implement [`From`](trait.from "From") and then fall back to [`Into`](trait.into "Into") if [`From`](trait.from "From") can’t be implemented. Examples -------- [`String`](../string/struct.string) implements [`Into`](trait.into "Into")`<`[`Vec`](../vec/struct.vec)`<`[`u8`](../primitive.u8 "u8")`>>`: In order to express that we want a generic function to take all arguments that can be converted to a specified type `T`, we can use a trait bound of [`Into`](trait.into "Into")`<T>`. For example: The function `is_hello` takes all arguments that can be converted into a [`Vec`](../vec/struct.vec)`<`[`u8`](../primitive.u8 "u8")`>`. ``` fn is_hello<T: Into<Vec<u8>>>(s: T) { let bytes = b"hello".to_vec(); assert_eq!(bytes, s.into()); } let s = "hello".to_string(); is_hello(s); ``` Required Methods ---------------- [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#280)#### fn into(self) -> T Converts this type into the (usually inferred) input type. Implementors ------------ [source](https://doc.rust-lang.org/src/std/process.rs.html#1661-1665)### impl Into<ExitStatus> for ExitStatusError [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · ### impl<T, U> Into<U> for Twhere U: [From](trait.from "trait std::convert::From")<T>, rust Trait std::convert::AsRef Trait std::convert::AsRef ========================= ``` pub trait AsRef<T>where    T: ?Sized,{ fn as_ref(&self) -> &T; } ``` Used to do a cheap reference-to-reference conversion. This trait is similar to [`AsMut`](trait.asmut "AsMut") which is used for converting between mutable references. If you need to do a costly conversion it is better to implement [`From`](trait.from "From") with type `&T` or write a custom function. `AsRef` has the same signature as [`Borrow`](../borrow/trait.borrow), but [`Borrow`](../borrow/trait.borrow) is different in a few aspects: * Unlike `AsRef`, [`Borrow`](../borrow/trait.borrow) has a blanket impl for any `T`, and can be used to accept either a reference or a value. * [`Borrow`](../borrow/trait.borrow) also requires that [`Hash`](../hash/trait.hash "Hash"), [`Eq`](../cmp/trait.eq) and [`Ord`](../cmp/trait.ord) for a borrowed value are equivalent to those of the owned value. For this reason, if you want to borrow only a single field of a struct you can implement `AsRef`, but not [`Borrow`](../borrow/trait.borrow). **Note: This trait must not fail**. If the conversion can fail, use a dedicated method which returns an [`Option<T>`](../option/enum.option "Option<T>") or a [`Result<T, E>`](../result/enum.result "Result<T, E>"). Generic Implementations ----------------------- * `AsRef` auto-dereferences if the inner type is a reference or a mutable reference (e.g.: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`) Examples -------- By using trait bounds we can accept arguments of different types as long as they can be converted to the specified type `T`. For example: By creating a generic function that takes an `AsRef<str>` we express that we want to accept all references that can be converted to [`&str`](../primitive.str) as an argument. Since both [`String`](../string/struct.string) and [`&str`](../primitive.str) implement `AsRef<str>` we can accept both as input argument. ``` fn is_hello<T: AsRef<str>>(s: T) { assert_eq!("hello", s.as_ref()); } let s = "hello"; is_hello(s); let s = "hello".to_string(); is_hello(s); ``` Required Methods ---------------- [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#161)#### fn as\_ref(&self) -> &T Converts this type into a shared reference of the (usually inferred) input type. Implementors ------------ [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#631)### impl AsRef<str> for str [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2596)### impl AsRef<str> for String [source](https://doc.rust-lang.org/src/core/ffi/c_str.rs.html#604)1.7.0 · ### impl AsRef<CStr> for CStr [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#1049)1.7.0 · ### impl AsRef<CStr> for CString [source](https://doc.rust-lang.org/src/std/path.rs.html#565-570)### impl AsRef<OsStr> for Component<'\_> [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1319-1324)### impl AsRef<OsStr> for str [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1303-1308)### impl AsRef<OsStr> for OsStr [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1311-1316)### impl AsRef<OsStr> for OsString [source](https://doc.rust-lang.org/src/std/path.rs.html#806-811)### impl AsRef<OsStr> for Components<'\_> [source](https://doc.rust-lang.org/src/std/path.rs.html#859-864)### impl AsRef<OsStr> for std::path::Iter<'\_> [source](https://doc.rust-lang.org/src/std/path.rs.html#2869-2874)### impl AsRef<OsStr> for Path [source](https://doc.rust-lang.org/src/std/path.rs.html#1880-1885)### impl AsRef<OsStr> for PathBuf [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1327-1332)### impl AsRef<OsStr> for String [source](https://doc.rust-lang.org/src/std/path.rs.html#3017-3022)1.8.0 · ### impl AsRef<Path> for Cow<'\_, OsStr> [source](https://doc.rust-lang.org/src/std/path.rs.html#573-578)1.25.0 · ### impl AsRef<Path> for Component<'\_> [source](https://doc.rust-lang.org/src/std/path.rs.html#3033-3038)### impl AsRef<Path> for str [source](https://doc.rust-lang.org/src/std/path.rs.html#3009-3014)### impl AsRef<Path> for OsStr [source](https://doc.rust-lang.org/src/std/path.rs.html#3025-3030)### impl AsRef<Path> for OsString [source](https://doc.rust-lang.org/src/std/path.rs.html#798-803)### impl AsRef<Path> for Components<'\_> [source](https://doc.rust-lang.org/src/std/path.rs.html#851-856)### impl AsRef<Path> for std::path::Iter<'\_> [source](https://doc.rust-lang.org/src/std/path.rs.html#3001-3006)### impl AsRef<Path> for Path [source](https://doc.rust-lang.org/src/std/path.rs.html#3049-3054)### impl AsRef<Path> for PathBuf [source](https://doc.rust-lang.org/src/std/path.rs.html#3041-3046)### impl AsRef<Path> for String [source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2563)### impl AsRef<[u8]> for str [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2612)### impl AsRef<[u8]> for String [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2914)1.55.0 · ### impl<'a> AsRef<str> for std::string::Drain<'a> [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2921)1.55.0 · ### impl<'a> AsRef<[u8]> for std::string::Drain<'a> [source](https://doc.rust-lang.org/src/alloc/vec/drain.rs.html#142)1.46.0 · ### impl<'a, T, A> AsRef<[T]> for std::vec::Drain<'a, T, A>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#617)### impl<T> AsRef<[T]> for [T] [source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#155)1.13.0 · ### impl<T> AsRef<[T]> for std::slice::Iter<'\_, T> [source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#353)1.53.0 · ### impl<T> AsRef<[T]> for IterMut<'\_, T> [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#433)### impl<T> AsRef<T> for Cow<'\_, T>where T: [ToOwned](../borrow/trait.toowned "trait std::borrow::ToOwned") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2671)1.5.0 · ### impl<T> AsRef<T> for Rc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2736)1.5.0 · ### impl<T> AsRef<T> for Arc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/vec/into_iter.rs.html#133)1.46.0 · ### impl<T, A> AsRef<[T]> for IntoIter<T, A>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2960)### impl<T, A> AsRef<[T]> for Vec<T, A>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2946)### impl<T, A> AsRef<Vec<T, A>> for Vec<T, A>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2004)1.5.0 · ### impl<T, A> AsRef<T> for Box<T, A>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#488)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · ### impl<T, U> AsRef<U> for &Twhere T: [AsRef](trait.asref "trait std::convert::AsRef")<U> + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), U: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#501)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · ### impl<T, U> AsRef<U> for &mut Twhere T: [AsRef](trait.asref "trait std::convert::AsRef")<U> + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), U: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vector.rs.html#576)### impl<T, const LANES: usize> AsRef<[T; LANES]> for Simd<T, LANES>where T: [SimdElement](../simd/trait.simdelement "trait std::simd::SimdElement"), [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vector.rs.html#599)### impl<T, const LANES: usize> AsRef<[T]> for Simd<T, LANES>where T: [SimdElement](../simd/trait.simdelement "trait std::simd::SimdElement"), [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/array/mod.rs.html#156)### impl<T, const N: usize> AsRef<[T]> for [T; N] rust Trait std::convert::FloatToInt Trait std::convert::FloatToInt ============================== ``` pub trait FloatToInt<Int>: Sealed { } ``` 🔬This is a nightly-only experimental API. (`convert_float_to_int` [#67057](https://github.com/rust-lang/rust/issues/67057)) Supporting trait for inherent methods of `f32` and `f64` such as `to_int_unchecked`. Typically doesn’t need to be used directly. Implementors ------------ [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)### impl FloatToInt<i8> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)### impl FloatToInt<i8> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)### impl FloatToInt<i16> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)### impl FloatToInt<i16> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)### impl FloatToInt<i32> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)### impl FloatToInt<i32> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)### impl FloatToInt<i64> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)### impl FloatToInt<i64> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)### impl FloatToInt<i128> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)### impl FloatToInt<i128> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)### impl FloatToInt<isize> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)### impl FloatToInt<isize> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)### impl FloatToInt<u8> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)### impl FloatToInt<u8> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)### impl FloatToInt<u16> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)### impl FloatToInt<u16> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)### impl FloatToInt<u32> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)### impl FloatToInt<u32> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)### impl FloatToInt<u64> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)### impl FloatToInt<u64> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)### impl FloatToInt<u128> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)### impl FloatToInt<u128> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)### impl FloatToInt<usize> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)### impl FloatToInt<usize> for f64 rust Trait std::convert::From Trait std::convert::From ======================== ``` pub trait From<T> { fn from(T) -> Self; } ``` Used to do value-to-value conversions while consuming the input value. It is the reciprocal of [`Into`](trait.into "Into"). One should always prefer implementing `From` over [`Into`](trait.into "Into") because implementing `From` automatically provides one with an implementation of [`Into`](trait.into "Into") thanks to the blanket implementation in the standard library. Only implement [`Into`](trait.into "Into") when targeting a version prior to Rust 1.41 and converting to a type outside the current crate. `From` was not able to do these types of conversions in earlier versions because of Rust’s orphaning rules. See [`Into`](trait.into "Into") for more details. Prefer using [`Into`](trait.into "Into") over using `From` when specifying trait bounds on a generic function. This way, types that directly implement [`Into`](trait.into "Into") can be used as arguments as well. The `From` is also very useful when performing error handling. When constructing a function that is capable of failing, the return type will generally be of the form `Result<T, E>`. The `From` trait simplifies error handling by allowing a function to return a single error type that encapsulate multiple error types. See the “Examples” section and [the book](../../book/ch09-00-error-handling) for more details. **Note: This trait must not fail**. The `From` trait is intended for perfect conversions. If the conversion can fail or is not perfect, use [`TryFrom`](trait.tryfrom "TryFrom"). Generic Implementations ----------------------- * `From<T> for U` implies [`Into`](trait.into "Into")`<U> for T` * `From` is reflexive, which means that `From<T> for T` is implemented Examples -------- [`String`](../string/struct.string) implements `From<&str>`: An explicit conversion from a `&str` to a String is done as follows: ``` let string = "hello".to_string(); let other_string = String::from("hello"); assert_eq!(string, other_string); ``` While performing error handling it is often useful to implement `From` for your own error type. By converting underlying error types to our own custom error type that encapsulates the underlying error type, we can return a single error type without losing information on the underlying cause. The ‘?’ operator automatically converts the underlying error type to our custom error type by calling `Into<CliError>::into` which is automatically provided when implementing `From`. The compiler then infers which implementation of `Into` should be used. ``` use std::fs; use std::io; use std::num; enum CliError { IoError(io::Error), ParseError(num::ParseIntError), } impl From<io::Error> for CliError { fn from(error: io::Error) -> Self { CliError::IoError(error) } } impl From<num::ParseIntError> for CliError { fn from(error: num::ParseIntError) -> Self { CliError::ParseError(error) } } fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> { let mut contents = fs::read_to_string(&file_name)?; let num: i32 = contents.trim().parse()?; Ok(num) } ``` Required Methods ---------------- [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#376)#### fn from(T) -> Self Converts to this type from the input type. Implementors ------------ [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1528)1.17.0 · ### impl From<&str> for Box<str, Global> [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2312)1.6.0 · ### impl From<&str> for Box<dyn Error + 'static, Global> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1899)1.21.0 · ### impl From<&str> for Rc<str> [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2621)### impl From<&str> for String [source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2503)1.21.0 · ### impl From<&str> for Arc<str> [source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3101)### impl From<&str> for Vec<u8, Global> [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#765)1.17.0 · ### impl From<&CStr> for Box<CStr, Global> [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#1032)1.7.0 · ### impl From<&CStr> for CString [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#900)1.24.0 · ### impl From<&CStr> for Rc<CStr> [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#878)1.24.0 · ### impl From<&CStr> for Arc<CStr> [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#985-992)1.17.0 · ### impl From<&OsStr> for Box<OsStr> [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1067-1074)1.24.0 · ### impl From<&OsStr> for Rc<OsStr> [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1046-1053)1.24.0 · ### impl From<&OsStr> for Arc<OsStr> [source](https://doc.rust-lang.org/src/std/path.rs.html#1580-1589)1.17.0 · ### impl From<&Path> for Box<Path> [source](https://doc.rust-lang.org/src/std/path.rs.html#1823-1830)1.24.0 · ### impl From<&Path> for Rc<Path> [source](https://doc.rust-lang.org/src/std/path.rs.html#1802-1809)1.24.0 · ### impl From<&Path> for Arc<Path> [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2645)1.35.0 · ### impl From<&String> for String [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2633)1.44.0 · ### impl From<&mut str> for String [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1548)1.45.0 · ### impl From<Cow<'\_, str>> for Box<str, Global> [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#775)1.45.0 · ### impl From<Cow<'\_, CStr>> for Box<CStr, Global> [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#995-1005)1.45.0 · ### impl From<Cow<'\_, OsStr>> for Box<OsStr> [source](https://doc.rust-lang.org/src/std/path.rs.html#1592-1603)1.45.0 · ### impl From<Cow<'\_, Path>> for Box<Path> [source](https://doc.rust-lang.org/src/alloc/collections/mod.rs.html#114)### impl From<TryReserveErrorKind> for TryReserveError [source](https://doc.rust-lang.org/src/std/io/error.rs.html#457-475)1.14.0 · ### impl From<ErrorKind> for Error Intended for use for errors not exposed to the user, where allocating onto the heap (for normal construction via Error::new) is too costly. [source](https://doc.rust-lang.org/src/core/array/mod.rs.html#149)1.36.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl From<Infallible> for TryFromSliceError [source](https://doc.rust-lang.org/src/core/num/error.rs.html#35)1.34.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl From<Infallible> for TryFromIntError [source](https://doc.rust-lang.org/src/std/net/ip_addr.rs.html#1147-1162)1.17.0 · ### impl From<[u8; 4]> for IpAddr [source](https://doc.rust-lang.org/src/std/net/ip_addr.rs.html#1129-1144)1.9.0 · ### impl From<[u8; 4]> for Ipv4Addr [source](https://doc.rust-lang.org/src/std/net/ip_addr.rs.html#2040-2066)1.17.0 · ### impl From<[u8; 16]> for IpAddr [source](https://doc.rust-lang.org/src/std/net/ip_addr.rs.html#1981-2007)1.9.0 · ### impl From<[u8; 16]> for Ipv6Addr [source](https://doc.rust-lang.org/src/std/net/ip_addr.rs.html#2069-2095)1.17.0 · ### impl From<[u16; 8]> for IpAddr [source](https://doc.rust-lang.org/src/std/net/ip_addr.rs.html#2010-2037)1.16.0 · ### impl From<[u16; 8]> for Ipv6Addr [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#92)1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<bool> for i8 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#93)1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<bool> for i16 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#94)1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<bool> for i32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#95)1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<bool> for i64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#96)1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<bool> for i128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#97)1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<bool> for isize [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#86)1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<bool> for u8 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#87)1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<bool> for u16 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#88)1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<bool> for u32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#89)1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<bool> for u64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#90)1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<bool> for u128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#91)1.28.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<bool> for usize [source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#1778)1.24.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl From<bool> for AtomicBool [source](https://doc.rust-lang.org/src/core/char/convert.rs.html#31)1.13.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl From<char> for u32 [source](https://doc.rust-lang.org/src/core/char/convert.rs.html#51)1.51.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl From<char> for u64 [source](https://doc.rust-lang.org/src/core/char/convert.rs.html#73)1.51.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl From<char> for u128 [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2959)1.46.0 · ### impl From<char> for String [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#169)1.6.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<f32> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#155)1.6.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i8> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#156)1.6.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i8> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#113)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i8> for i16 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#114)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i8> for i32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#115)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i8> for i64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#116)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i8> for i128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#117)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i8> for isize [source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#2675-2693)1.34.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i8> for AtomicI8 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#157)1.6.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i16> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#158)1.6.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i16> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#118)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i16> for i32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#119)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i16> for i64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#120)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i16> for i128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#142)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i16> for isize [source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#2715-2733)1.34.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i16> for AtomicI16 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#159)1.6.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i32> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#121)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i32> for i64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#122)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i32> for i128 [source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#2755-2773)1.34.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i32> for AtomicI32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#123)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i64> for i128 [source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#2795-2813)1.34.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<i64> for AtomicI64 [source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#2922-2926)1.23.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<isize> for AtomicIsize [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)1.34.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl From<!> for Infallible [source](https://doc.rust-lang.org/src/core/num/error.rs.html#42)### impl From<!> for TryFromIntError [source](https://doc.rust-lang.org/src/core/char/convert.rs.html#127)1.13.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl From<u8> for char Maps a byte in 0x00..=0xFF to a `char` whose code point has the same value, in U+0000..=U+00FF. Unicode is designed such that this effectively decodes bytes with the character encoding that IANA calls ISO-8859-1. This encoding is compatible with ASCII. Note that this is different from ISO/IEC 8859-1 a.k.a. ISO 8859-1 (with one less hyphen), which leaves some “blanks”, byte values that are not assigned to any character. ISO-8859-1 (the IANA one) assigns them to the C0 and C1 control codes. Note that this is *also* different from Windows-1252 a.k.a. code page 1252, which is a superset ISO/IEC 8859-1 that assigns some (not all!) blanks to punctuation and various Latin characters. To confuse things further, [on the Web](https://encoding.spec.whatwg.org/) `ascii`, `iso-8859-1`, and `windows-1252` are all aliases for a superset of Windows-1252 that fills the remaining blanks with corresponding C0 and C1 control codes. [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#162)1.6.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u8> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#163)1.6.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u8> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#126)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u8> for i16 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#127)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u8> for i32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#128)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u8> for i64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#129)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u8> for i128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#141)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u8> for isize [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#100)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u8> for u16 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#101)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u8> for u32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#102)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u8> for u64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#103)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u8> for u128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#104)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u8> for usize [source](https://doc.rust-lang.org/src/std/process.rs.html#1814-1819)1.61.0 · ### impl From<u8> for ExitCode [source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#2695-2713)1.34.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u8> for AtomicU8 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#164)1.6.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u16> for f32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#165)1.6.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u16> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#130)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u16> for i32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#131)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u16> for i64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#132)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u16> for i128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#105)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u16> for u32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#106)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u16> for u64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#107)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u16> for u128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#140)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u16> for usize [source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#2735-2753)1.34.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u16> for AtomicU16 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#166)1.6.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u32> for f64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#133)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u32> for i64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#134)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u32> for i128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#108)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u32> for u64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#109)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u32> for u128 [source](https://doc.rust-lang.org/src/std/net/ip_addr.rs.html#1111-1126)1.1.0 · ### impl From<u32> for Ipv4Addr [source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#2775-2793)1.34.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u32> for AtomicU32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#135)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u64> for i128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#110)1.26.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u64> for u128 [source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#2815-2833)1.34.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<u64> for AtomicU64 [source](https://doc.rust-lang.org/src/std/net/ip_addr.rs.html#1958-1978)1.26.0 · ### impl From<u128> for Ipv6Addr [source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#2922-2926)1.23.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<usize> for AtomicUsize [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#29)### impl From<\_\_m128> for Simd<f32, 4> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#39)### impl From<\_\_m128d> for Simd<f64, 2> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#12)### impl From<\_\_m128i> for Simd<i8, 16> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#19)### impl From<\_\_m128i> for Simd<i16, 8> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#26)### impl From<\_\_m128i> for Simd<i32, 4> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#36)### impl From<\_\_m128i> for Simd<i64, 2> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#60)### impl From<\_\_m128i> for Simd<isize, 2> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#9)### impl From<\_\_m128i> for Simd<u8, 16> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#16)### impl From<\_\_m128i> for Simd<u16, 8> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#23)### impl From<\_\_m128i> for Simd<u32, 4> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#33)### impl From<\_\_m128i> for Simd<u64, 2> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#57)### impl From<\_\_m128i> for Simd<usize, 2> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#30)### impl From<\_\_m256> for Simd<f32, 8> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#40)### impl From<\_\_m256d> for Simd<f64, 4> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#13)### impl From<\_\_m256i> for Simd<i8, 32> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#20)### impl From<\_\_m256i> for Simd<i16, 16> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#27)### impl From<\_\_m256i> for Simd<i32, 8> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#37)### impl From<\_\_m256i> for Simd<i64, 4> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#61)### impl From<\_\_m256i> for Simd<isize, 4> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#10)### impl From<\_\_m256i> for Simd<u8, 32> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#17)### impl From<\_\_m256i> for Simd<u16, 16> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#24)### impl From<\_\_m256i> for Simd<u32, 8> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#34)### impl From<\_\_m256i> for Simd<u64, 4> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#58)### impl From<\_\_m256i> for Simd<usize, 4> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#31)### impl From<\_\_m512> for Simd<f32, 16> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#41)### impl From<\_\_m512d> for Simd<f64, 8> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#14)### impl From<\_\_m512i> for Simd<i8, 64> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#21)### impl From<\_\_m512i> for Simd<i16, 32> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#28)### impl From<\_\_m512i> for Simd<i32, 16> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#38)### impl From<\_\_m512i> for Simd<i64, 8> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#62)### impl From<\_\_m512i> for Simd<isize, 8> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#11)### impl From<\_\_m512i> for Simd<u8, 64> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#18)### impl From<\_\_m512i> for Simd<u16, 32> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#25)### impl From<\_\_m512i> for Simd<u32, 16> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#35)### impl From<\_\_m512i> for Simd<u64, 8> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#59)### impl From<\_\_m512i> for Simd<usize, 8> [source](https://doc.rust-lang.org/src/alloc/collections/mod.rs.html#122)### impl From<LayoutError> for TryReserveErrorKind [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2658)1.18.0 · ### impl From<Box<str, Global>> for String [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#788)1.18.0 · ### impl From<Box<CStr, Global>> for CString [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1008-1015)1.18.0 · ### impl From<Box<OsStr, Global>> for OsString [source](https://doc.rust-lang.org/src/std/path.rs.html#1606-1614)1.18.0 · ### impl From<Box<Path, Global>> for PathBuf [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#829)1.20.0 · ### impl From<CString> for Box<CStr, Global> [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#889)1.24.0 · ### impl From<CString> for Rc<CStr> [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#866)1.24.0 · ### impl From<CString> for Arc<CStr> [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#726)1.7.0 · ### impl From<CString> for Vec<u8, Global> [source](https://doc.rust-lang.org/src/std/io/error.rs.html#81-86)### impl From<NulError> for Error [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1018-1024)1.20.0 · ### impl From<OsString> for Box<OsStr> [source](https://doc.rust-lang.org/src/std/path.rs.html#1648-1656)### impl From<OsString> for PathBuf [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1056-1064)1.24.0 · ### impl From<OsString> for Rc<OsStr> [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1035-1043)1.24.0 · ### impl From<OsString> for Arc<OsStr> [source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#267-272)1.63.0 · ### impl From<File> for OwnedFd [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#451-456)1.63.0 · ### impl From<File> for OwnedHandle Available on **Windows** only.[source](https://doc.rust-lang.org/src/std/process.rs.html#1397-1421)1.20.0 · ### impl From<File> for Stdio [source](https://doc.rust-lang.org/src/std/net/ip_addr.rs.html#947-966)1.16.0 · ### impl From<Ipv4Addr> for IpAddr [source](https://doc.rust-lang.org/src/std/net/ip_addr.rs.html#1093-1108)1.1.0 · ### impl From<Ipv4Addr> for u32 [source](https://doc.rust-lang.org/src/std/net/ip_addr.rs.html#969-988)1.16.0 · ### impl From<Ipv6Addr> for IpAddr [source](https://doc.rust-lang.org/src/std/net/ip_addr.rs.html#1938-1956)1.26.0 · ### impl From<Ipv6Addr> for u128 [source](https://doc.rust-lang.org/src/std/net/socket_addr.rs.html#573-578)1.16.0 · ### impl From<SocketAddrV4> for SocketAddr [source](https://doc.rust-lang.org/src/std/net/socket_addr.rs.html#581-586)1.16.0 · ### impl From<SocketAddrV6> for SocketAddr [source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#317-322)1.63.0 · ### impl From<TcpListener> for OwnedFd [source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#301-306)1.63.0 · ### impl From<TcpListener> for OwnedSocket Available on **Windows** only.[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#291-296)1.63.0 · ### impl From<TcpStream> for OwnedFd [source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#277-282)1.63.0 · ### impl From<TcpStream> for OwnedSocket Available on **Windows** only.[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#343-348)1.63.0 · ### impl From<UdpSocket> for OwnedFd [source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#325-330)1.63.0 · ### impl From<UdpSocket> for OwnedSocket Available on **Windows** only.[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#161-174)1.31.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI8> for i8 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#433)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI8> for NonZeroI16 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#434)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI8> for NonZeroI32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#435)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI8> for NonZeroI64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#436)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI8> for NonZeroI128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#437)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI8> for NonZeroIsize [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#161-174)1.31.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI16> for i16 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#438)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI16> for NonZeroI32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#439)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI16> for NonZeroI64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#440)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI16> for NonZeroI128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#441)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI16> for NonZeroIsize [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#161-174)1.31.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI32> for i32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#442)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI32> for NonZeroI64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#443)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI32> for NonZeroI128 [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#161-174)1.31.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI64> for i64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#444)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI64> for NonZeroI128 [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#161-174)1.31.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroI128> for i128 [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#161-174)1.31.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroIsize> for isize [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#161-174)1.31.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU8> for u8 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#447)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU8> for NonZeroI16 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#448)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU8> for NonZeroI32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#449)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU8> for NonZeroI64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#450)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU8> for NonZeroI128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#451)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU8> for NonZeroIsize [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#419)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU8> for NonZeroU16 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#420)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU8> for NonZeroU32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#421)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU8> for NonZeroU64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#422)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU8> for NonZeroU128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#423)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU8> for NonZeroUsize [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#161-174)1.31.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU16> for u16 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#452)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU16> for NonZeroI32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#453)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU16> for NonZeroI64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#454)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU16> for NonZeroI128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#424)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU16> for NonZeroU32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#425)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU16> for NonZeroU64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#426)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU16> for NonZeroU128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#427)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU16> for NonZeroUsize [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#161-174)1.31.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU32> for u32 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#455)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU32> for NonZeroI64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#456)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU32> for NonZeroI128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#428)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU32> for NonZeroU64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#429)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU32> for NonZeroU128 [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#161-174)1.31.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU64> for u64 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#457)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU64> for NonZeroI128 [source](https://doc.rust-lang.org/src/core/convert/num.rs.html#430)1.41.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU64> for NonZeroU128 [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#161-174)1.31.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroU128> for u128 [source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#161-174)1.31.0 (const: [unstable](https://github.com/rust-lang/rust/issues/87852 "Tracking issue for const_num_from_num")) · ### impl From<NonZeroUsize> for usize [source](https://doc.rust-lang.org/src/std/os/linux/process.rs.html#102-106)### impl From<PidFd> for OwnedFd Available on **Linux** only.[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#275-280)1.63.0 · ### impl From<OwnedFd> for File [source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#325-332)1.63.0 · ### impl From<OwnedFd> for TcpListener [source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#299-306)1.63.0 · ### impl From<OwnedFd> for TcpStream [source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#351-358)1.63.0 · ### impl From<OwnedFd> for UdpSocket [source](https://doc.rust-lang.org/src/std/os/linux/process.rs.html#96-100)### impl From<OwnedFd> for PidFd Available on **Linux** only.[source](https://doc.rust-lang.org/src/std/os/unix/net/datagram.rs.html#1007-1012)1.63.0 · ### impl From<OwnedFd> for UnixDatagram Available on **Unix** only.[source](https://doc.rust-lang.org/src/std/os/unix/net/listener.rs.html#318-323)1.63.0 · ### impl From<OwnedFd> for UnixListener Available on **Unix** only.[source](https://doc.rust-lang.org/src/std/os/unix/net/stream.rs.html#731-736)1.63.0 · ### impl From<OwnedFd> for UnixStream Available on **Unix** only.[source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#356-363)1.63.0 · ### impl From<OwnedFd> for Stdio Available on **Unix** only.[source](https://doc.rust-lang.org/src/std/os/unix/net/datagram.rs.html#999-1004)1.63.0 · ### impl From<UnixDatagram> for OwnedFd Available on **Unix** only.[source](https://doc.rust-lang.org/src/std/os/unix/net/listener.rs.html#326-331)1.63.0 · ### impl From<UnixListener> for OwnedFd Available on **Unix** only.[source](https://doc.rust-lang.org/src/std/os/unix/net/stream.rs.html#723-728)1.63.0 · ### impl From<UnixStream> for OwnedFd Available on **Unix** only.[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#459-464)1.63.0 · ### impl From<OwnedHandle> for File Available on **Windows** only.[source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#26-32)1.63.0 · ### impl From<OwnedHandle> for Stdio Available on **Windows** only.[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#309-314)1.63.0 · ### impl From<OwnedSocket> for TcpListener Available on **Windows** only.[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#285-290)1.63.0 · ### impl From<OwnedSocket> for TcpStream Available on **Windows** only.[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#333-338)1.63.0 · ### impl From<OwnedSocket> for UdpSocket Available on **Windows** only.[source](https://doc.rust-lang.org/src/std/path.rs.html#1617-1626)1.20.0 · ### impl From<PathBuf> for Box<Path> [source](https://doc.rust-lang.org/src/std/path.rs.html#1659-1667)1.14.0 · ### impl From<PathBuf> for OsString [source](https://doc.rust-lang.org/src/std/path.rs.html#1812-1820)1.24.0 · ### impl From<PathBuf> for Rc<Path> [source](https://doc.rust-lang.org/src/std/path.rs.html#1791-1799)1.24.0 · ### impl From<PathBuf> for Arc<Path> [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#58-62)1.63.0 · ### impl From<Child> for OwnedHandle Available on **Windows** only.[source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#454-459)1.63.0 · ### impl From<ChildStderr> for OwnedFd Available on **Unix** only.[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#555-560)1.63.0 · ### impl From<ChildStderr> for OwnedHandle Available on **Windows** only.[source](https://doc.rust-lang.org/src/std/process.rs.html#1366-1394)1.20.0 · ### impl From<ChildStderr> for Stdio [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#422-427)1.63.0 · ### impl From<ChildStdin> for OwnedFd Available on **Unix** only.[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#523-528)1.63.0 · ### impl From<ChildStdin> for OwnedHandle Available on **Windows** only.[source](https://doc.rust-lang.org/src/std/process.rs.html#1308-1334)1.20.0 · ### impl From<ChildStdin> for Stdio [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#438-443)1.63.0 · ### impl From<ChildStdout> for OwnedFd Available on **Unix** only.[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#539-544)1.63.0 · ### impl From<ChildStdout> for OwnedHandle Available on **Windows** only.[source](https://doc.rust-lang.org/src/std/process.rs.html#1337-1363)1.20.0 · ### impl From<ChildStdout> for Stdio [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2008)1.62.0 · ### impl From<Rc<str>> for Rc<[u8]> [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#29)### impl From<Simd<f32, 4>> for \_\_m128 [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#30)### impl From<Simd<f32, 8>> for \_\_m256 [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#31)### impl From<Simd<f32, 16>> for \_\_m512 [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#39)### impl From<Simd<f64, 2>> for \_\_m128d [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#40)### impl From<Simd<f64, 4>> for \_\_m256d [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#41)### impl From<Simd<f64, 8>> for \_\_m512d [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#12)### impl From<Simd<i8, 16>> for \_\_m128i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#13)### impl From<Simd<i8, 32>> for \_\_m256i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#14)### impl From<Simd<i8, 64>> for \_\_m512i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#19)### impl From<Simd<i16, 8>> for \_\_m128i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#20)### impl From<Simd<i16, 16>> for \_\_m256i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#21)### impl From<Simd<i16, 32>> for \_\_m512i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#26)### impl From<Simd<i32, 4>> for \_\_m128i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#27)### impl From<Simd<i32, 8>> for \_\_m256i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#28)### impl From<Simd<i32, 16>> for \_\_m512i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#36)### impl From<Simd<i64, 2>> for \_\_m128i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#37)### impl From<Simd<i64, 4>> for \_\_m256i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#38)### impl From<Simd<i64, 8>> for \_\_m512i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#60)### impl From<Simd<isize, 2>> for \_\_m128i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#61)### impl From<Simd<isize, 4>> for \_\_m256i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#62)### impl From<Simd<isize, 8>> for \_\_m512i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#9)### impl From<Simd<u8, 16>> for \_\_m128i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#10)### impl From<Simd<u8, 32>> for \_\_m256i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#11)### impl From<Simd<u8, 64>> for \_\_m512i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#16)### impl From<Simd<u16, 8>> for \_\_m128i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#17)### impl From<Simd<u16, 16>> for \_\_m256i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#18)### impl From<Simd<u16, 32>> for \_\_m512i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#23)### impl From<Simd<u32, 4>> for \_\_m128i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#24)### impl From<Simd<u32, 8>> for \_\_m256i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#25)### impl From<Simd<u32, 16>> for \_\_m512i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#33)### impl From<Simd<u64, 2>> for \_\_m128i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#34)### impl From<Simd<u64, 4>> for \_\_m256i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#35)### impl From<Simd<u64, 8>> for \_\_m512i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#57)### impl From<Simd<usize, 2>> for \_\_m128i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#58)### impl From<Simd<usize, 4>> for \_\_m256i [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vendor/x86.rs.html#59)### impl From<Simd<usize, 8>> for \_\_m512i [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2680)1.20.0 · ### impl From<String> for Box<str, Global> [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2264)1.6.0 · ### impl From<String> for Box<dyn Error + 'static, Global> [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2219)### impl From<String> for Box<dyn Error + Send + Sync + 'static, Global> [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#472-480)### impl From<String> for OsString [source](https://doc.rust-lang.org/src/std/path.rs.html#1670-1678)### impl From<String> for PathBuf [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1918)1.21.0 · ### impl From<String> for Rc<str> [source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2522)1.21.0 · ### impl From<String> for Arc<str> [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2814)1.14.0 · ### impl From<String> for Vec<u8, Global> [source](https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#1658-1669)1.24.0 · ### impl From<RecvError> for RecvTimeoutError [source](https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#1623-1634)1.24.0 · ### impl From<RecvError> for TryRecvError [source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2612)1.62.0 · ### impl From<Arc<str>> for Arc<[u8]> [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#798)1.43.0 · ### impl From<Vec<NonZeroU8, Global>> for CString [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2725)### impl<'a> From<&'a str> for Cow<'a, str> [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#847)1.28.0 · ### impl<'a> From<&'a CStr> for Cow<'a, CStr> [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#856)1.28.0 · ### impl<'a> From<&'a CString> for Cow<'a, CStr> [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1086-1092)1.28.0 · ### impl<'a> From<&'a OsStr> for Cow<'a, OsStr> [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1095-1101)1.28.0 · ### impl<'a> From<&'a OsString> for Cow<'a, OsStr> [source](https://doc.rust-lang.org/src/std/path.rs.html#1744-1753)1.6.0 · ### impl<'a> From<&'a Path> for Cow<'a, Path> [source](https://doc.rust-lang.org/src/std/path.rs.html#1768-1777)1.28.0 · ### impl<'a> From<&'a PathBuf> for Cow<'a, Path> [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2769)1.28.0 · ### impl<'a> From<&'a String> for Cow<'a, str> [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2287)### impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a, Global> [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2358)1.22.0 · ### impl<'a> From<Cow<'a, str>> for Box<dyn Error + 'static, Global> [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2701)1.14.0 · ### impl<'a> From<Cow<'a, str>> for String [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#754)1.28.0 · ### impl<'a> From<Cow<'a, CStr>> for CString [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1104-1111)1.28.0 · ### impl<'a> From<Cow<'a, OsStr>> for OsString [source](https://doc.rust-lang.org/src/std/path.rs.html#1780-1788)1.28.0 · ### impl<'a> From<Cow<'a, Path>> for PathBuf [source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#838)1.28.0 · ### impl<'a> From<CString> for Cow<'a, CStr> [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1077-1083)1.28.0 · ### impl<'a> From<OsString> for Cow<'a, OsStr> [source](https://doc.rust-lang.org/src/std/path.rs.html#1756-1765)1.6.0 · ### impl<'a> From<PathBuf> for Cow<'a, Path> [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2746)### impl<'a> From<String> for Cow<'a, str> [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2335)1.22.0 · ### impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a, Global> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1981)1.45.0 · ### impl<'a, B> From<Cow<'a, B>> for Rc<B>where B: [ToOwned](../borrow/trait.toowned "trait std::borrow::ToOwned") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [Rc](../rc/struct.rc "struct std::rc::Rc")<B>: [From](trait.from "trait std::convert::From")<[&'a](../primitive.reference) B>, [Rc](../rc/struct.rc "struct std::rc::Rc")<B>: [From](trait.from "trait std::convert::From")<<B as [ToOwned](../borrow/trait.toowned "trait std::borrow::ToOwned")>::[Owned](../borrow/trait.toowned#associatedtype.Owned "type std::borrow::ToOwned::Owned")>, [source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2585)1.45.0 · ### impl<'a, B> From<Cow<'a, B>> for Arc<B>where B: [ToOwned](../borrow/trait.toowned "trait std::borrow::ToOwned") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [Arc](../sync/struct.arc "struct std::sync::Arc")<B>: [From](trait.from "trait std::convert::From")<[&'a](../primitive.reference) B>, [Arc](../sync/struct.arc "struct std::sync::Arc")<B>: [From](trait.from "trait std::convert::From")<<B as [ToOwned](../borrow/trait.toowned "trait std::borrow::ToOwned")>::[Owned](../borrow/trait.toowned#associatedtype.Owned "type std::borrow::ToOwned::Owned")>, [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2145)### impl<'a, E> From<E> for Box<dyn Error + 'a, Global>where E: 'a + [Error](../error/trait.error "trait std::error::Error"), [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2179)### impl<'a, E> From<E> for Box<dyn Error + Send + Sync + 'a, Global>where E: 'a + [Error](../error/trait.error "trait std::error::Error") + [Send](../marker/trait.send "trait std::marker::Send") + [Sync](../marker/trait.sync "trait std::marker::Sync"), [source](https://doc.rust-lang.org/src/core/option.rs.html#1990)1.30.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl<'a, T> From<&'a Option<T>> for Option<&'a T> [source](https://doc.rust-lang.org/src/alloc/vec/cow.rs.html#7)1.8.0 · ### impl<'a, T> From<&'a [T]> for Cow<'a, [T]>where T: [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/alloc/vec/cow.rs.html#33)1.28.0 · ### impl<'a, T> From<&'a Vec<T, Global>> for Cow<'a, [T]>where T: [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/core/option.rs.html#2018)1.30.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> [source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3038)1.14.0 · ### impl<'a, T> From<Cow<'a, [T]>> for Vec<T, Global>where [[T]](../primitive.slice): [ToOwned](../borrow/trait.toowned "trait std::borrow::ToOwned"), <[[T]](../primitive.slice) as [ToOwned](../borrow/trait.toowned "trait std::borrow::ToOwned")>::[Owned](../borrow/trait.toowned#associatedtype.Owned "type std::borrow::ToOwned::Owned") == [Vec](../vec/struct.vec "struct std::vec::Vec")<T, [Global](../alloc/struct.global "struct std::alloc::Global")>, [source](https://doc.rust-lang.org/src/alloc/vec/cow.rs.html#20)1.8.0 · ### impl<'a, T> From<Vec<T, Global>> for Cow<'a, [T]>where T: [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/std/io/readbuf.rs.html#52-64)### impl<'data> From<&'data mut [u8]> for BorrowedBuf<'data> Create a new `BorrowedBuf` from a fully initialized slice. [source](https://doc.rust-lang.org/src/std/io/readbuf.rs.html#69-74)### impl<'data> From<&'data mut [MaybeUninit<u8>]> for BorrowedBuf<'data> Create a new `BorrowedBuf` from an uninitialized buffer. Use `set_init` if part of the buffer is known to be already initialized. [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1582)1.19.0 · ### impl<A> From<Box<str, A>> for Box<[u8], A>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/std/error.rs.html#1547-1554)### impl<E> From<E> for Report<E>where E: [Error](../error/trait.error "trait std::error::Error"), [source](https://doc.rust-lang.org/src/std/net/socket_addr.rs.html#589-599)1.17.0 · ### impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr [source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1357-1373)1.56.0 · ### impl<K, V, const N: usize> From<[(K, V); N]> for HashMap<K, V, RandomState>where K: [Eq](../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../hash/trait.hash "trait std::hash::Hash"), [source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#2224)1.56.0 · ### impl<K, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V, Global>where K: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1484)1.17.0 · ### impl<T> From<&[T]> for Box<[T], Global>where T: [Copy](../marker/trait.copy "trait std::marker::Copy"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1880)1.21.0 · ### impl<T> From<&[T]> for Rc<[T]>where T: [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2484)1.21.0 · ### impl<T> From<&[T]> for Arc<[T]>where T: [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2975)### impl<T> From<&[T]> for Vec<T, Global>where T: [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2995)1.19.0 · ### impl<T> From<&mut [T]> for Vec<T, Global>where T: [Clone](../clone/trait.clone "trait std::clone::Clone"), [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1510)1.45.0 · ### impl<T> From<Cow<'\_, [T]>> for Box<[T], Global>where T: [Copy](../marker/trait.copy "trait std::marker::Copy"), [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#577)1.34.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl<T> From<!> for T **Stability note:** This impl does not yet exist, but we are “reserving space” to add it in the future. See [rust-lang/rust#64715](https://github.com/rust-lang/rust/issues/64715) for details. [source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#1797)1.23.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl<T> From<\*mut T> for AtomicPtr<T> [source](https://doc.rust-lang.org/src/core/ptr/non_null.rs.html#792)1.25.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl<T> From<&T> for NonNull<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/ptr/non_null.rs.html#779)1.25.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl<T> From<&mut T> for NonNull<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1937)1.21.0 · ### impl<T> From<Box<T, Global>> for Rc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2541)1.21.0 · ### impl<T> From<Box<T, Global>> for Arc<T>where T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1602)1.5.0 · ### impl<T> From<BinaryHeap<T>> for Vec<T, Global> [source](https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#1573-1584)1.24.0 · ### impl<T> From<SendError<T>> for TrySendError<T> [source](https://doc.rust-lang.org/src/std/sync/poison.rs.html#218-222)### impl<T> From<PoisonError<T>> for TryLockError<T> [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#571-576)1.63.0 · ### impl<T> From<JoinHandle<T>> for OwnedHandle Available on **Windows** only.[source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1574)1.5.0 · ### impl<T> From<Vec<T, Global>> for BinaryHeap<T>where T: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1956)1.21.0 · ### impl<T> From<Vec<T, Global>> for Rc<[T]> [source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2560)1.21.0 · ### impl<T> From<Vec<T, Global>> for Arc<[T]> [source](https://doc.rust-lang.org/src/core/option.rs.html#1973)1.12.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl<T> From<T> for Option<T> [source](https://doc.rust-lang.org/src/core/task/poll.rs.html#245)1.36.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl<T> From<T> for Poll<T> [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1441)1.6.0 · ### impl<T> From<T> for Box<T, Global> [source](https://doc.rust-lang.org/src/core/cell.rs.html#325)1.12.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl<T> From<T> for Cell<T> [source](https://doc.rust-lang.org/src/core/cell/once.rs.html#278)### impl<T> From<T> for OnceCell<T> [source](https://doc.rust-lang.org/src/core/cell.rs.html#1257)1.12.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl<T> From<T> for RefCell<T> [source](https://doc.rust-lang.org/src/core/cell.rs.html#2100)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · ### impl<T> From<T> for SyncUnsafeCell<T> [source](https://doc.rust-lang.org/src/core/cell.rs.html#2010)1.12.0 (const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert")) · ### impl<T> From<T> for UnsafeCell<T> [source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1859)1.6.0 · ### impl<T> From<T> for Rc<T> [source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2462)1.6.0 · ### impl<T> From<T> for Arc<T> [source](https://doc.rust-lang.org/src/core/sync/exclusive.rs.html#160)### impl<T> From<T> for Exclusive<T> [source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#459-465)1.24.0 · ### impl<T> From<T> for Mutex<T> [source](https://doc.rust-lang.org/src/std/sync/once_lock.rs.html#391-416)### impl<T> From<T> for OnceLock<T> [source](https://doc.rust-lang.org/src/std/sync/rwlock.rs.html#513-519)1.24.0 · ### impl<T> From<T> for RwLock<T> [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · ### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3064)1.18.0 · ### impl<T, A> From<Box<[T], A>> for Vec<T, A>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1462)1.33.0 (const: [unstable](https://github.com/rust-lang/rust/issues/92521 "Tracking issue for const_box")) · ### impl<T, A> From<Box<T, A>> for Pin<Box<T, A>>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator") + 'static, T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3065)1.10.0 · ### impl<T, A> From<VecDeque<T, A>> for Vec<T, A>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3083)1.20.0 · ### impl<T, A> From<Vec<T, A>> for Box<[T], A>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3030)1.10.0 · ### impl<T, A> From<Vec<T, A>> for VecDeque<T, A>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#259)### impl<T, const LANES: usize> From<[bool; LANES]> for Mask<T, LANES>where T: [MaskElement](../simd/trait.maskelement "trait std::simd::MaskElement"), [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vector.rs.html#622)### impl<T, const LANES: usize> From<[T; LANES]> for Simd<T, LANES>where T: [SimdElement](../simd/trait.simdelement "trait std::simd::SimdElement"), [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#269)### impl<T, const LANES: usize> From<Mask<T, LANES>> for [bool; LANES]where T: [MaskElement](../simd/trait.maskelement "trait std::simd::MaskElement"), [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vector.rs.html#632)### impl<T, const LANES: usize> From<Simd<T, LANES>> for [T; LANES]where T: [SimdElement](../simd/trait.simdelement "trait std::simd::SimdElement"), [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks/full_masks.rs.html#260)### impl<T, const LANES: usize> From<Mask<T, LANES>> for Simd<T, LANES>where T: [MaskElement](../simd/trait.maskelement "trait std::simd::MaskElement"), [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1608)1.45.0 · ### impl<T, const N: usize> From<[T; N]> for Box<[T], Global> [source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1048-1064)1.56.0 · ### impl<T, const N: usize> From<[T; N]> for HashSet<T, RandomState>where T: [Eq](../cmp/trait.eq "trait std::cmp::Eq") + [Hash](../hash/trait.hash "trait std::hash::Hash"), [source](https://doc.rust-lang.org/src/alloc/collections/btree/set.rs.html#1226)1.56.0 · ### impl<T, const N: usize> From<[T; N]> for BTreeSet<T, Global>where T: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/binary_heap.rs.html#1586)1.56.0 · ### impl<T, const N: usize> From<[T; N]> for BinaryHeap<T>where T: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), [source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1955)1.56.0 · ### impl<T, const N: usize> From<[T; N]> for LinkedList<T> [source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#3114)1.56.0 · ### impl<T, const N: usize> From<[T; N]> for VecDeque<T, Global> [source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3015)1.44.0 · ### impl<T, const N: usize> From<[T; N]> for Vec<T, Global> [source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#483-489)### impl<T: ?Sized + AsRef<OsStr>> From<&T> for OsString [source](https://doc.rust-lang.org/src/std/path.rs.html#1637-1645)### impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf [source](https://doc.rust-lang.org/src/std/io/buffered/mod.rs.html#177-181)### impl<W> From<IntoInnerError<W>> for Error [source](https://doc.rust-lang.org/src/alloc/task.rs.html#101)1.51.0 · ### impl<W> From<Arc<W>> for RawWakerwhere W: 'static + [Wake](../task/trait.wake "trait std::task::Wake") + [Send](../marker/trait.send "trait std::marker::Send") + [Sync](../marker/trait.sync "trait std::marker::Sync"), [source](https://doc.rust-lang.org/src/alloc/task.rs.html#89)1.51.0 · ### impl<W> From<Arc<W>> for Wakerwhere W: 'static + [Wake](../task/trait.wake "trait std::task::Wake") + [Send](../marker/trait.send "trait std::marker::Send") + [Sync](../marker/trait.sync "trait std::marker::Sync"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#591)### impl<const LANES: usize> From<Mask<i8, LANES>> for Mask<i16, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#591)### impl<const LANES: usize> From<Mask<i8, LANES>> for Mask<i32, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#591)### impl<const LANES: usize> From<Mask<i8, LANES>> for Mask<i64, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#591)### impl<const LANES: usize> From<Mask<i8, LANES>> for Mask<isize, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#592)### impl<const LANES: usize> From<Mask<i16, LANES>> for Mask<i8, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#592)### impl<const LANES: usize> From<Mask<i16, LANES>> for Mask<i32, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#592)### impl<const LANES: usize> From<Mask<i16, LANES>> for Mask<i64, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#592)### impl<const LANES: usize> From<Mask<i16, LANES>> for Mask<isize, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#593)### impl<const LANES: usize> From<Mask<i32, LANES>> for Mask<i8, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#593)### impl<const LANES: usize> From<Mask<i32, LANES>> for Mask<i16, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#593)### impl<const LANES: usize> From<Mask<i32, LANES>> for Mask<i64, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#593)### impl<const LANES: usize> From<Mask<i32, LANES>> for Mask<isize, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#594)### impl<const LANES: usize> From<Mask<i64, LANES>> for Mask<i8, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#594)### impl<const LANES: usize> From<Mask<i64, LANES>> for Mask<i16, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#594)### impl<const LANES: usize> From<Mask<i64, LANES>> for Mask<i32, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#594)### impl<const LANES: usize> From<Mask<i64, LANES>> for Mask<isize, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#595)### impl<const LANES: usize> From<Mask<isize, LANES>> for Mask<i8, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#595)### impl<const LANES: usize> From<Mask<isize, LANES>> for Mask<i16, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#595)### impl<const LANES: usize> From<Mask<isize, LANES>> for Mask<i32, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/masks.rs.html#595)### impl<const LANES: usize> From<Mask<isize, LANES>> for Mask<i64, LANES>where [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"),
programming_docs
rust Trait std::convert::AsMut Trait std::convert::AsMut ========================= ``` pub trait AsMut<T>where    T: ?Sized,{ fn as_mut(&mut self) -> &mut T; } ``` Used to do a cheap mutable-to-mutable reference conversion. This trait is similar to [`AsRef`](trait.asref "AsRef") but used for converting between mutable references. If you need to do a costly conversion it is better to implement [`From`](trait.from "From") with type `&mut T` or write a custom function. **Note: This trait must not fail**. If the conversion can fail, use a dedicated method which returns an [`Option<T>`](../option/enum.option "Option<T>") or a [`Result<T, E>`](../result/enum.result "Result<T, E>"). Generic Implementations ----------------------- * `AsMut` auto-dereferences if the inner type is a mutable reference (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo` or `&mut &mut Foo`) Examples -------- Using `AsMut` as trait bound for a generic function we can accept all mutable references that can be converted to type `&mut T`. Because [`Box<T>`](../boxed/struct.box) implements `AsMut<T>` we can write a function `add_one` that takes all arguments that can be converted to `&mut u64`. Because [`Box<T>`](../boxed/struct.box) implements `AsMut<T>`, `add_one` accepts arguments of type `&mut Box<u64>` as well: ``` fn add_one<T: AsMut<u64>>(num: &mut T) { *num.as_mut() += 1; } let mut boxed_num = Box::new(0); add_one(&mut boxed_num); assert_eq!(*boxed_num, 1); ``` Required Methods ---------------- [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#203)#### fn as\_mut(&mut self) -> &mut T Converts this type into a mutable reference of the (usually inferred) input type. Implementors ------------ [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#639)1.51.0 · ### impl AsMut<str> for str [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2604)1.43.0 · ### impl AsMut<str> for String [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#624)### impl<T> AsMut<[T]> for [T] [source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2967)1.5.0 · ### impl<T, A> AsMut<[T]> for Vec<T, A>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2953)1.5.0 · ### impl<T, A> AsMut<Vec<T, A>> for Vec<T, A>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), [source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2011)1.5.0 · ### impl<T, A> AsMut<T> for Box<T, A>where A: [Allocator](../alloc/trait.allocator "trait std::alloc::Allocator"), T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#522)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · ### impl<T, U> AsMut<U> for &mut Twhere T: [AsMut](trait.asmut "trait std::convert::AsMut")<U> + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), U: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vector.rs.html#587)### impl<T, const LANES: usize> AsMut<[T; LANES]> for Simd<T, LANES>where T: [SimdElement](../simd/trait.simdelement "trait std::simd::SimdElement"), [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/up/up/portable-simd/crates/core_simd/src/vector.rs.html#610)### impl<T, const LANES: usize> AsMut<[T]> for Simd<T, LANES>where T: [SimdElement](../simd/trait.simdelement "trait std::simd::SimdElement"), [LaneCount](../simd/struct.lanecount "struct std::simd::LaneCount")<LANES>: [SupportedLaneCount](../simd/trait.supportedlanecount "trait std::simd::SupportedLaneCount"), [source](https://doc.rust-lang.org/src/core/array/mod.rs.html#164)### impl<T, const N: usize> AsMut<[T]> for [T; N] rust Function std::process::abort Function std::process::abort ============================ ``` pub fn abort() -> ! ``` Terminates the process in an abnormal fashion. The function will never return and will immediately terminate the current process in a platform specific “abnormal” manner. Note that because this function never returns, and that it terminates the process, no destructors on the current stack or any other thread’s stack will be run. Rust IO buffers (eg, from `BufWriter`) will not be flushed. Likewise, C stdio buffers will (on most platforms) not be flushed. This is in contrast to the default behaviour of [`panic!`](../macro.panic "panic!") which unwinds the current thread’s stack and calls all destructors. When `panic="abort"` is set, either as an argument to `rustc` or in a crate’s Cargo.toml, [`panic!`](../macro.panic "panic!") and `abort` are similar. However, [`panic!`](../macro.panic "panic!") will still call the [panic hook](../panic/fn.set_hook) while `abort` will not. If a clean shutdown is needed it is recommended to only call this function at a known point where there are no more destructors left to run. The process’s termination will be similar to that from the C `abort()` function. On Unix, the process will terminate with signal `SIGABRT`, which typically means that the shell prints “Aborted”. Examples -------- ``` use std::process; fn main() { println!("aborting"); process::abort(); // execution never gets here } ``` The `abort` function terminates the process, so the destructor will not get run on the example below: ``` use std::process; struct HasDrop; impl Drop for HasDrop { fn drop(&mut self) { println!("This will never be printed!"); } } fn main() { let _x = HasDrop; process::abort(); // the destructor implemented for HasDrop will never get run } ``` rust Struct std::process::ExitCode Struct std::process::ExitCode ============================= ``` pub struct ExitCode(_); ``` This type represents the status code the current process can return to its parent under normal termination. `ExitCode` is intended to be consumed only by the standard library (via [`Termination::report()`](trait.termination#tymethod.report "Termination::report()")), and intentionally does not provide accessors like `PartialEq`, `Eq`, or `Hash`. Instead the standard library provides the canonical `SUCCESS` and `FAILURE` exit codes as well as `From<u8> for ExitCode` for constructing other arbitrary exit codes. Portability ----------- Numeric values used in this type don’t have portable meanings, and different platforms may mask different amounts of them. For the platform’s canonical successful and unsuccessful codes, see the [`SUCCESS`](struct.exitcode#associatedconstant.SUCCESS) and [`FAILURE`](struct.exitcode#associatedconstant.FAILURE) associated items. Differences from `ExitStatus` ----------------------------- `ExitCode` is intended for terminating the currently running process, via the `Termination` trait, in contrast to [`ExitStatus`](struct.exitstatus "ExitStatus"), which represents the termination of a child process. These APIs are separate due to platform compatibility differences and their expected usage; it is not generally possible to exactly reproduce an `ExitStatus` from a child for the current process after the fact. Examples -------- `ExitCode` can be returned from the `main` function of a crate, as it implements [`Termination`](trait.termination "Termination"): ``` use std::process::ExitCode; fn main() -> ExitCode { if !check_foo() { return ExitCode::from(42); } ExitCode::SUCCESS } ``` Implementations --------------- [source](https://doc.rust-lang.org/src/std/process.rs.html#1732-1791)### impl ExitCode [source](https://doc.rust-lang.org/src/std/process.rs.html#1739)#### pub const SUCCESS: ExitCode = \_ The canonical `ExitCode` for successful termination on this platform. Note that a `()`-returning `main` implicitly results in a successful termination, so there’s no need to return this from `main` unless you’re also returning other possible codes. [source](https://doc.rust-lang.org/src/std/process.rs.html#1747)#### pub const FAILURE: ExitCode = \_ The canonical `ExitCode` for unsuccessful termination on this platform. If you’re only returning this and `SUCCESS` from `main`, consider instead returning `Err(_)` and `Ok(())` respectively, which will return the same codes (but will also `eprintln!` the error). [source](https://doc.rust-lang.org/src/std/process.rs.html#1788-1790)#### pub fn exit\_process(self) -> ! 🔬This is a nightly-only experimental API. (`exitcode_exit_method` [#97100](https://github.com/rust-lang/rust/issues/97100)) Exit the current process with the given `ExitCode`. Note that this has the same caveats as [`process::exit()`](fn.exit "exit"), namely that this function terminates the process immediately, so no destructors on the current stack or any other thread’s stack will be run. If a clean shutdown is needed, it is recommended to simply return this ExitCode from the `main` function, as demonstrated in the [type documentation](#examples). ##### Differences from `process::exit()` `process::exit()` accepts any `i32` value as the exit code for the process; however, there are platforms that only use a subset of that value (see [`process::exit` platform-specific behavior](fn.exit#platform-specific-behavior "exit")). `ExitCode` exists because of this; only `ExitCode`s that are supported by a majority of our platforms can be created, so those problems don’t exist (as much) with this method. ##### Examples ``` #![feature(exitcode_exit_method)] // there's no way to gracefully recover from an UhOhError, so we just // print a message and exit fn handle_unrecoverable_error(err: UhOhError) -> ! { eprintln!("UH OH! {err}"); let code = match err { UhOhError::GenericProblem => ExitCode::FAILURE, UhOhError::Specific => ExitCode::from(3), UhOhError::WithCode { exit_code, .. } => exit_code, }; code.exit_process() } ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/process.rs.html#1723)### impl Clone for ExitCode [source](https://doc.rust-lang.org/src/std/process.rs.html#1723)#### fn clone(&self) -> ExitCode Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/process.rs.html#1723)### impl Debug for ExitCode [source](https://doc.rust-lang.org/src/std/process.rs.html#1723)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#255-259)### impl ExitCodeExt for ExitCode Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#256-258)#### fn from\_raw(raw: u32) -> Self 🔬This is a nightly-only experimental API. (`windows_process_exit_code_from`) Creates a new `ExitCode` from the raw underlying `u32` return value of a process. [Read more](../os/windows/process/trait.exitcodeext#tymethod.from_raw) [source](https://doc.rust-lang.org/src/std/process.rs.html#1814-1819)### impl From<u8> for ExitCode [source](https://doc.rust-lang.org/src/std/process.rs.html#1816-1818)#### fn from(code: u8) -> Self Construct an `ExitCode` from an arbitrary u8 value. [source](https://doc.rust-lang.org/src/std/process.rs.html#2190-2195)### impl Termination for ExitCode [source](https://doc.rust-lang.org/src/std/process.rs.html#2192-2194)#### fn report(self) -> ExitCode Is called to get the representation of the value as status code. This status code is returned to the operating system. [Read more](trait.termination#tymethod.report) [source](https://doc.rust-lang.org/src/std/process.rs.html#1723)### impl Copy for ExitCode Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for ExitCode ### impl Send for ExitCode ### impl Sync for ExitCode ### impl Unpin for ExitCode ### impl UnwindSafe for ExitCode Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Struct std::process::ChildStdout Struct std::process::ChildStdout ================================ ``` pub struct ChildStdout { /* private fields */ } ``` A handle to a child process’s standard output (stdout). This struct is used in the [`stdout`](struct.child#structfield.stdout) field on [`Child`](struct.child "Child"). When an instance of `ChildStdout` is [dropped](../ops/trait.drop), the `ChildStdout`’s underlying file handle will be closed. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#430-435)1.63.0 · ### impl AsFd for ChildStdout Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#432-434)#### fn as\_fd(&self) -> BorrowedFd<'\_> Borrows the file descriptor. [Read more](../os/unix/io/trait.asfd#tymethod.as_fd) [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#531-536)1.63.0 · ### impl AsHandle for ChildStdout Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#533-535)#### fn as\_handle(&self) -> BorrowedHandle<'\_> Borrows the handle. [Read more](../os/windows/io/trait.ashandle#tymethod.as_handle) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#374-379)1.2.0 · ### impl AsRawFd for ChildStdout Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#376-378)#### fn as\_raw\_fd(&self) -> RawFd Extracts the raw file descriptor. [Read more](../os/unix/io/trait.asrawfd#tymethod.as_raw_fd) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#73-78)1.2.0 · ### impl AsRawHandle for ChildStdout Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#75-77)#### fn as\_raw\_handle(&self) -> RawHandle Extracts the raw handle. [Read more](../os/windows/io/trait.asrawhandle#tymethod.as_raw_handle) [source](https://doc.rust-lang.org/src/std/process.rs.html#386-390)1.16.0 · ### impl Debug for ChildStdout [source](https://doc.rust-lang.org/src/std/process.rs.html#387-389)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#438-443)1.63.0 · ### impl From<ChildStdout> for OwnedFd Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#440-442)#### fn from(child\_stdout: ChildStdout) -> OwnedFd Converts to this type from the input type. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#539-544)1.63.0 · ### impl From<ChildStdout> for OwnedHandle Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#541-543)#### fn from(child\_stdout: ChildStdout) -> OwnedHandle Converts to this type from the input type. [source](https://doc.rust-lang.org/src/std/process.rs.html#1337-1363)1.20.0 · ### impl From<ChildStdout> for Stdio [source](https://doc.rust-lang.org/src/std/process.rs.html#1360-1362)#### fn from(child: ChildStdout) -> Stdio Converts a [`ChildStdout`](struct.childstdout "ChildStdout") into a [`Stdio`](struct.stdio "Stdio"). ##### Examples `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood. ``` use std::process::{Command, Stdio}; let hello = Command::new("echo") .arg("Hello, world!") .stdout(Stdio::piped()) .spawn() .expect("failed echo command"); let reverse = Command::new("rev") .stdin(hello.stdout.unwrap()) // Converted into a Stdio here .output() .expect("failed reverse command"); assert_eq!(reverse.stdout, b"!dlrow ,olleH\n"); ``` [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#398-403)1.4.0 · ### impl IntoRawFd for ChildStdout Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#400-402)#### fn into\_raw\_fd(self) -> RawFd Consumes this object, returning the raw underlying file descriptor. [Read more](../os/unix/io/trait.intorawfd#tymethod.into_raw_fd) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#96-100)1.4.0 · ### impl IntoRawHandle for ChildStdout Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#97-99)#### fn into\_raw\_handle(self) -> RawHandle Consumes this object, returning the raw underlying handle. [Read more](../os/windows/io/trait.intorawhandle#tymethod.into_raw_handle) [source](https://doc.rust-lang.org/src/std/process.rs.html#352-365)### impl Read for ChildStdout [source](https://doc.rust-lang.org/src/std/process.rs.html#353-355)#### fn read(&mut self, buf: &mut [u8]) -> Result<usize> Pull some bytes from this source into the specified buffer, returning how many bytes were read. [Read more](../io/trait.read#tymethod.read) [source](https://doc.rust-lang.org/src/std/process.rs.html#357-359)#### fn read\_vectored(&mut self, bufs: &mut [IoSliceMut<'\_>]) -> Result<usize> Like `read`, except that it reads into a slice of buffers. [Read more](../io/trait.read#method.read_vectored) [source](https://doc.rust-lang.org/src/std/process.rs.html#362-364)#### fn is\_read\_vectored(&self) -> bool 🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941)) Determines if this `Read`er has an efficient `read_vectored` implementation. [Read more](../io/trait.read#method.is_read_vectored) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#706-708)#### fn read\_to\_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> Read all bytes until EOF in this source, placing them into `buf`. [Read more](../io/trait.read#method.read_to_end) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#749-751)#### fn read\_to\_string(&mut self, buf: &mut String) -> Result<usize> Read all bytes until EOF in this source, appending them to `buf`. [Read more](../io/trait.read#method.read_to_string) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#804-806)1.6.0 · #### fn read\_exact(&mut self, buf: &mut [u8]) -> Result<()> Read the exact number of bytes required to fill `buf`. [Read more](../io/trait.read#method.read_exact) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#815-817)#### fn read\_buf(&mut self, buf: BorrowedCursor<'\_>) -> Result<()> 🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485)) Pull some bytes from this source into the specified buffer. [Read more](../io/trait.read#method.read_buf) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#824-839)#### fn read\_buf\_exact(&mut self, cursor: BorrowedCursor<'\_>) -> Result<()> 🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485)) Read the exact number of bytes required to fill `cursor`. [Read more](../io/trait.read#method.read_buf_exact) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#876-881)#### fn by\_ref(&mut self) -> &mut Selfwhere Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Creates a “by reference” adaptor for this instance of `Read`. [Read more](../io/trait.read#method.by_ref) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#919-924)#### fn bytes(self) -> Bytes<Self>where Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Bytes](../io/struct.bytes "struct std::io::Bytes")<R> ``` impl<R: Read> Iterator for Bytes<R> type Item = Result<u8>; ``` Transforms this `Read` instance to an [`Iterator`](../iter/trait.iterator "Iterator") over its bytes. [Read more](../io/trait.read#method.bytes) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#957-962)#### fn chain<R: Read>(self, next: R) -> Chain<Self, R>where Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Chain](../io/struct.chain "struct std::io::Chain")<T, U> ``` impl<T: Read, U: Read> Read for Chain<T, U> ``` Creates an adapter which will chain this stream with another. [Read more](../io/trait.read#method.chain) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#996-1001)#### fn take(self, limit: u64) -> Take<Self>where Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Take](../io/struct.take "struct std::io::Take")<T> ``` impl<T: Read> Read for Take<T> ``` Creates an adapter which will read at most `limit` bytes from it. [Read more](../io/trait.read#method.take) Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for ChildStdout ### impl Send for ChildStdout ### impl Sync for ChildStdout ### impl Unpin for ChildStdout ### impl UnwindSafe for ChildStdout Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Module std::process Module std::process =================== A module for working with processes. This module is mostly concerned with spawning and interacting with child processes, but it also provides [`abort`](fn.abort "abort") and [`exit`](fn.exit "exit") for terminating the current process. Spawning a process ------------------ The [`Command`](struct.command "Command") struct is used to configure and spawn processes: ``` use std::process::Command; let output = Command::new("echo") .arg("Hello world") .output() .expect("Failed to execute command"); assert_eq!(b"Hello world\n", output.stdout.as_slice()); ``` Several methods on [`Command`](struct.command "Command"), such as [`spawn`](struct.command#method.spawn) or [`output`](struct.command#method.output), can be used to spawn a process. In particular, [`output`](struct.command#method.output) spawns the child process and waits until the process terminates, while [`spawn`](struct.command#method.spawn) will return a [`Child`](struct.child "Child") that represents the spawned child process. Handling I/O ------------ The [`stdout`](struct.command#method.stdout), [`stdin`](struct.command#method.stdin), and [`stderr`](struct.command#method.stderr) of a child process can be configured by passing an [`Stdio`](struct.stdio "Stdio") to the corresponding method on [`Command`](struct.command "Command"). Once spawned, they can be accessed from the [`Child`](struct.child "Child"). For example, piping output from one command into another command can be done like so: ``` use std::process::{Command, Stdio}; // stdout must be configured with `Stdio::piped` in order to use // `echo_child.stdout` let echo_child = Command::new("echo") .arg("Oh no, a tpyo!") .stdout(Stdio::piped()) .spawn() .expect("Failed to start echo process"); // Note that `echo_child` is moved here, but we won't be needing // `echo_child` anymore let echo_out = echo_child.stdout.expect("Failed to open echo stdout"); let mut sed_child = Command::new("sed") .arg("s/tpyo/typo/") .stdin(Stdio::from(echo_out)) .stdout(Stdio::piped()) .spawn() .expect("Failed to start sed process"); let output = sed_child.wait_with_output().expect("Failed to wait on sed"); assert_eq!(b"Oh no, a typo!\n", output.stdout.as_slice()); ``` Note that [`ChildStderr`](struct.childstderr "ChildStderr") and [`ChildStdout`](struct.childstdout "ChildStdout") implement [`Read`](../io/trait.read) and [`ChildStdin`](struct.childstdin "ChildStdin") implements [`Write`](../io/trait.write): ``` use std::process::{Command, Stdio}; use std::io::Write; let mut child = Command::new("/bin/cat") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() .expect("failed to execute child"); // If the child process fills its stdout buffer, it may end up // waiting until the parent reads the stdout, and not be able to // read stdin in the meantime, causing a deadlock. // Writing from another thread ensures that stdout is being read // at the same time, avoiding the problem. let mut stdin = child.stdin.take().expect("failed to get stdin"); std::thread::spawn(move || { stdin.write_all(b"test").expect("failed to write to stdin"); }); let output = child .wait_with_output() .expect("failed to wait on child"); assert_eq!(b"test", output.stdout.as_slice()); ``` Structs ------- [ExitStatusError](struct.exitstatuserror "std::process::ExitStatusError struct")Experimental Describes the result of a process after it has failed [Child](struct.child "std::process::Child struct") Representation of a running or exited child process. [ChildStderr](struct.childstderr "std::process::ChildStderr struct") A handle to a child process’s stderr. [ChildStdin](struct.childstdin "std::process::ChildStdin struct") A handle to a child process’s standard input (stdin). [ChildStdout](struct.childstdout "std::process::ChildStdout struct") A handle to a child process’s standard output (stdout). [Command](struct.command "std::process::Command struct") A process builder, providing fine-grained control over how a new process should be spawned. [CommandArgs](struct.commandargs "std::process::CommandArgs struct") An iterator over the command arguments. [CommandEnvs](struct.commandenvs "std::process::CommandEnvs struct") An iterator over the command environment variables. [ExitCode](struct.exitcode "std::process::ExitCode struct") This type represents the status code the current process can return to its parent under normal termination. [ExitStatus](struct.exitstatus "std::process::ExitStatus struct") Describes the result of a process after it has terminated. [Output](struct.output "std::process::Output struct") The output of a finished process. [Stdio](struct.stdio "std::process::Stdio struct") Describes what to do with a standard I/O stream for a child process when passed to the [`stdin`](struct.command#method.stdin), [`stdout`](struct.command#method.stdout), and [`stderr`](struct.command#method.stderr) methods of [`Command`](struct.command "Command"). Traits ------ [Termination](trait.termination "std::process::Termination trait") A trait for implementing arbitrary return types in the `main` function. Functions --------- [abort](fn.abort "std::process::abort fn") Terminates the process in an abnormal fashion. [exit](fn.exit "std::process::exit fn") Terminates the current process with the specified exit code. [id](fn.id "std::process::id fn") Returns the OS-assigned process identifier associated with this process. rust Struct std::process::ExitStatus Struct std::process::ExitStatus =============================== ``` pub struct ExitStatus(_); ``` Describes the result of a process after it has terminated. This `struct` is used to represent the exit status or other termination of a child process. Child processes are created via the [`Command`](struct.command "Command") struct and their exit status is exposed through the [`status`](struct.command#method.status) method, or the [`wait`](struct.child#method.wait) method of a [`Child`](struct.child "Child") process. An `ExitStatus` represents every possible disposition of a process. On Unix this is the **wait status**. It is *not* simply an *exit status* (a value passed to `exit`). For proper error reporting of failed processes, print the value of `ExitStatus` or `ExitStatusError` using their implementations of [`Display`](../fmt/trait.display). Differences from `ExitCode` --------------------------- [`ExitCode`](struct.exitcode "ExitCode") is intended for terminating the currently running process, via the `Termination` trait, in contrast to `ExitStatus`, which represents the termination of a child process. These APIs are separate due to platform compatibility differences and their expected usage; it is not generally possible to exactly reproduce an `ExitStatus` from a child for the current process after the fact. Implementations --------------- [source](https://doc.rust-lang.org/src/std/process.rs.html#1460-1540)### impl ExitStatus [source](https://doc.rust-lang.org/src/std/process.rs.html#1480-1482)#### pub fn exit\_ok(&self) -> Result<(), ExitStatusError> 🔬This is a nightly-only experimental API. (`exit_status_error` [#84908](https://github.com/rust-lang/rust/issues/84908)) Was termination successful? Returns a `Result`. ##### Examples ``` #![feature(exit_status_error)] use std::process::Command; let status = Command::new("ls") .arg("/dev/nonexistent") .status() .expect("ls could not be executed"); println!("ls: {status}"); status.exit_ok().expect_err("/dev/nonexistent could be listed!"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1505-1507)#### pub fn success(&self) -> bool Was termination successful? Signal termination is not considered a success, and success is defined as a zero exit status. ##### Examples ``` use std::process::Command; let status = Command::new("mkdir") .arg("projects") .status() .expect("failed to execute mkdir"); if status.success() { println!("'projects/' directory created"); } else { println!("failed to create 'projects/' directory: {status}"); } ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1537-1539)#### pub fn code(&self) -> Option<i32> Returns the exit code of the process, if any. In Unix terms the return value is the **exit status**: the value passed to `exit`, if the process finished by calling `exit`. Note that on Unix the exit status is truncated to 8 bits, and that values that didn’t come from a program’s call to `exit` may be invented by the runtime system (often, for example, 255, 254, 127 or 126). On Unix, this will return `None` if the process was terminated by a signal. [`ExitStatusExt`](../os/unix/process/trait.exitstatusext) is an extension trait for extracting any such signal, and other details, from the `ExitStatus`. ##### Examples ``` use std::process::Command; let status = Command::new("mkdir") .arg("projects") .status() .expect("failed to execute mkdir"); match status.code() { Some(code) => println!("Exited with status code: {code}"), None => println!("Process terminated by signal") } ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/process.rs.html#1452)### impl Clone for ExitStatus [source](https://doc.rust-lang.org/src/std/process.rs.html#1452)#### fn clone(&self) -> ExitStatus Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/process.rs.html#1452)### impl Debug for ExitStatus [source](https://doc.rust-lang.org/src/std/process.rs.html#1452)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/process.rs.html#1555-1559)### impl Display for ExitStatus [source](https://doc.rust-lang.org/src/std/process.rs.html#1556-1558)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#290-314)### impl ExitStatusExt for ExitStatus Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#291-293)#### fn from\_raw(raw: i32) -> Self Creates a new `ExitStatus` or `ExitStatusError` from the raw underlying integer status value from `wait` [Read more](../os/unix/process/trait.exitstatusext#tymethod.from_raw) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#295-297)#### fn signal(&self) -> Option<i32> If the process was terminated by a signal, returns that signal. [Read more](../os/unix/process/trait.exitstatusext#tymethod.signal) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#299-301)#### fn core\_dumped(&self) -> bool If the process was terminated by a signal, says whether it dumped core. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#303-305)#### fn stopped\_signal(&self) -> Option<i32> If the process was stopped by a signal, returns that signal. [Read more](../os/unix/process/trait.exitstatusext#tymethod.stopped_signal) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#307-309)#### fn continued(&self) -> bool Whether the process was continued from a stopped status. [Read more](../os/unix/process/trait.exitstatusext#tymethod.continued) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#311-313)#### fn into\_raw(self) -> i32 Returns the underlying raw `wait` status. [Read more](../os/unix/process/trait.exitstatusext#tymethod.into_raw) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#122-126)1.12.0 · ### impl ExitStatusExt for ExitStatus Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#123-125)#### fn from\_raw(raw: u32) -> Self Creates a new `ExitStatus` from the raw underlying `u32` return value of a process. [Read more](../os/windows/process/trait.exitstatusext#tymethod.from_raw) [source](https://doc.rust-lang.org/src/std/process.rs.html#1661-1665)### impl Into<ExitStatus> for ExitStatusError [source](https://doc.rust-lang.org/src/std/process.rs.html#1662-1664)#### fn into(self) -> ExitStatus Converts this type into the (usually inferred) input type. [source](https://doc.rust-lang.org/src/std/process.rs.html#1452)### impl PartialEq<ExitStatus> for ExitStatus [source](https://doc.rust-lang.org/src/std/process.rs.html#1452)#### fn eq(&self, other: &ExitStatus) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/std/process.rs.html#1452)### impl Copy for ExitStatus [source](https://doc.rust-lang.org/src/std/process.rs.html#1452)### impl Eq for ExitStatus [source](https://doc.rust-lang.org/src/std/process.rs.html#1452)### impl StructuralEq for ExitStatus [source](https://doc.rust-lang.org/src/std/process.rs.html#1452)### impl StructuralPartialEq for ExitStatus Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for ExitStatus ### impl Send for ExitStatus ### impl Sync for ExitStatus ### impl Unpin for ExitStatus ### impl UnwindSafe for ExitStatus Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2500)### impl<T> ToString for Twhere T: [Display](../fmt/trait.display "trait std::fmt::Display") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2506)#### default fn to\_string(&self) -> String Converts the given value to a `String`. [Read more](../string/trait.tostring#tymethod.to_string) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Struct std::process::Stdio Struct std::process::Stdio ========================== ``` pub struct Stdio(_); ``` Describes what to do with a standard I/O stream for a child process when passed to the [`stdin`](struct.command#method.stdin), [`stdout`](struct.command#method.stdout), and [`stderr`](struct.command#method.stderr) methods of [`Command`](struct.command "Command"). Implementations --------------- [source](https://doc.rust-lang.org/src/std/process.rs.html#1144-1292)### impl Stdio [source](https://doc.rust-lang.org/src/std/process.rs.html#1193-1195)#### pub fn piped() -> Stdio A new pipe should be arranged to connect the parent and child processes. ##### Examples With stdout: ``` use std::process::{Command, Stdio}; let output = Command::new("echo") .arg("Hello, world!") .stdout(Stdio::piped()) .output() .expect("Failed to execute command"); assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n"); // Nothing echoed to console ``` With stdin: ``` use std::io::Write; use std::process::{Command, Stdio}; let mut child = Command::new("rev") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() .expect("Failed to spawn child process"); let mut stdin = child.stdin.take().expect("Failed to open stdin"); std::thread::spawn(move || { stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin"); }); let output = child.wait_with_output().expect("Failed to read stdout"); assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH"); ``` Writing more than a pipe buffer’s worth of input to stdin without also reading stdout and stderr at the same time may cause a deadlock. This is an issue when running any program that doesn’t guarantee that it reads its entire stdin before writing more than a pipe buffer’s worth of output. The size of a pipe buffer varies on different targets. [source](https://doc.rust-lang.org/src/std/process.rs.html#1233-1235)#### pub fn inherit() -> Stdio The child inherits from the corresponding parent descriptor. ##### Examples With stdout: ``` use std::process::{Command, Stdio}; let output = Command::new("echo") .arg("Hello, world!") .stdout(Stdio::inherit()) .output() .expect("Failed to execute command"); assert_eq!(String::from_utf8_lossy(&output.stdout), ""); // "Hello, world!" echoed to console ``` With stdin: ``` use std::process::{Command, Stdio}; use std::io::{self, Write}; let output = Command::new("rev") .stdin(Stdio::inherit()) .stdout(Stdio::piped()) .output() .expect("Failed to execute command"); print!("You piped in the reverse of: "); io::stdout().write_all(&output.stdout).unwrap(); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1273-1275)#### pub fn null() -> Stdio This stream will be ignored. This is the equivalent of attaching the stream to `/dev/null`. ##### Examples With stdout: ``` use std::process::{Command, Stdio}; let output = Command::new("echo") .arg("Hello, world!") .stdout(Stdio::null()) .output() .expect("Failed to execute command"); assert_eq!(String::from_utf8_lossy(&output.stdout), ""); // Nothing echoed to console ``` With stdin: ``` use std::process::{Command, Stdio}; let output = Command::new("rev") .stdin(Stdio::null()) .stdout(Stdio::piped()) .output() .expect("Failed to execute command"); assert_eq!(String::from_utf8_lossy(&output.stdout), ""); // Ignores any piped-in input ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1289-1291)#### pub fn makes\_pipe(&self) -> bool 🔬This is a nightly-only experimental API. (`stdio_makes_pipe` [#98288](https://github.com/rust-lang/rust/issues/98288)) Returns `true` if this requires [`Command`](struct.command "Command") to create a new pipe. ##### Example ``` #![feature(stdio_makes_pipe)] use std::process::Stdio; let io = Stdio::piped(); assert_eq!(io.makes_pipe(), true); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/process.rs.html#1301-1305)1.16.0 · ### impl Debug for Stdio [source](https://doc.rust-lang.org/src/std/process.rs.html#1302-1304)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/process.rs.html#1366-1394)1.20.0 · ### impl From<ChildStderr> for Stdio [source](https://doc.rust-lang.org/src/std/process.rs.html#1391-1393)#### fn from(child: ChildStderr) -> Stdio Converts a [`ChildStderr`](struct.childstderr "ChildStderr") into a [`Stdio`](struct.stdio "Stdio"). ##### Examples ``` use std::process::{Command, Stdio}; let reverse = Command::new("rev") .arg("non_existing_file.txt") .stderr(Stdio::piped()) .spawn() .expect("failed reverse command"); let cat = Command::new("cat") .arg("-") .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here .output() .expect("failed echo command"); assert_eq!( String::from_utf8_lossy(&cat.stdout), "rev: cannot open non_existing_file.txt: No such file or directory\n" ); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1308-1334)1.20.0 · ### impl From<ChildStdin> for Stdio [source](https://doc.rust-lang.org/src/std/process.rs.html#1331-1333)#### fn from(child: ChildStdin) -> Stdio Converts a [`ChildStdin`](struct.childstdin "ChildStdin") into a [`Stdio`](struct.stdio "Stdio"). ##### Examples `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood. ``` use std::process::{Command, Stdio}; let reverse = Command::new("rev") .stdin(Stdio::piped()) .spawn() .expect("failed reverse command"); let _echo = Command::new("echo") .arg("Hello, world!") .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here .output() .expect("failed echo command"); // "!dlrow ,olleH" echoed to console ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1337-1363)1.20.0 · ### impl From<ChildStdout> for Stdio [source](https://doc.rust-lang.org/src/std/process.rs.html#1360-1362)#### fn from(child: ChildStdout) -> Stdio Converts a [`ChildStdout`](struct.childstdout "ChildStdout") into a [`Stdio`](struct.stdio "Stdio"). ##### Examples `ChildStdout` will be converted to `Stdio` using `Stdio::from` under the hood. ``` use std::process::{Command, Stdio}; let hello = Command::new("echo") .arg("Hello, world!") .stdout(Stdio::piped()) .spawn() .expect("failed echo command"); let reverse = Command::new("rev") .stdin(hello.stdout.unwrap()) // Converted into a Stdio here .output() .expect("failed reverse command"); assert_eq!(reverse.stdout, b"!dlrow ,olleH\n"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1397-1421)1.20.0 · ### impl From<File> for Stdio [source](https://doc.rust-lang.org/src/std/process.rs.html#1418-1420)#### fn from(file: File) -> Stdio Converts a [`File`](../fs/struct.file) into a [`Stdio`](struct.stdio "Stdio"). ##### Examples `File` will be converted to `Stdio` using `Stdio::from` under the hood. ``` use std::fs::File; use std::process::Command; // With the `foo.txt` file containing `Hello, world!" let file = File::open("foo.txt").unwrap(); let reverse = Command::new("rev") .stdin(file) // Implicit File conversion into a Stdio .output() .expect("failed reverse command"); assert_eq!(reverse.stdout, b"!dlrow ,olleH"); ``` [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#356-363)1.63.0 · ### impl From<OwnedFd> for Stdio Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#358-362)#### fn from(fd: OwnedFd) -> Stdio Converts to this type from the input type. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#26-32)1.63.0 · ### impl From<OwnedHandle> for Stdio Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#27-31)#### fn from(handle: OwnedHandle) -> Stdio Converts to this type from the input type. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#346-353)1.2.0 · ### impl FromRawFd for Stdio Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#348-352)#### unsafe fn from\_raw\_fd(fd: RawFd) -> Stdio Constructs a new instance of `Self` from the given raw file descriptor. [Read more](../os/unix/io/trait.fromrawfd#tymethod.from_raw_fd) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#17-23)1.2.0 · ### impl FromRawHandle for Stdio Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#18-22)#### unsafe fn from\_raw\_handle(handle: RawHandle) -> Stdio Constructs a new I/O object from the specified raw handle. [Read more](../os/windows/io/trait.fromrawhandle#tymethod.from_raw_handle) Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for Stdio ### impl Send for Stdio ### impl Sync for Stdio ### impl Unpin for Stdio ### impl UnwindSafe for Stdio Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::process::Child Struct std::process::Child ========================== ``` pub struct Child { pub stdin: Option<ChildStdin>, pub stdout: Option<ChildStdout>, pub stderr: Option<ChildStderr>, /* private fields */ } ``` Representation of a running or exited child process. This structure is used to represent and manage child processes. A child process is created via the [`Command`](struct.command "Command") struct, which configures the spawning process and can itself be constructed using a builder-style interface. There is no implementation of [`Drop`](../ops/trait.drop "Drop") for child processes, so if you do not ensure the `Child` has exited then it will continue to run, even after the `Child` handle to the child process has gone out of scope. Calling [`wait`](struct.child#method.wait) (or other functions that wrap around it) will make the parent process wait until the child has actually exited before continuing. Warning ------- On some systems, calling [`wait`](struct.child#method.wait) or similar is necessary for the OS to release resources. A process that terminated but has not been waited on is still around as a “zombie”. Leaving too many zombies around may exhaust global resources (for example process IDs). The standard library does *not* automatically wait on child processes (not even if the `Child` is dropped), it is up to the application developer to do so. As a consequence, dropping `Child` handles without waiting on them first is not recommended in long-running applications. Examples -------- ⓘ ``` use std::process::Command; let mut child = Command::new("/bin/cat") .arg("file.txt") .spawn() .expect("failed to execute child"); let ecode = child.wait() .expect("failed to wait on child"); assert!(ecode.success()); ``` Fields ------ `stdin: [Option](../option/enum.option "enum std::option::Option")<[ChildStdin](struct.childstdin "struct std::process::ChildStdin")>`The handle for writing to the child’s standard input (stdin), if it has been captured. You might find it helpful to do ⓘ ``` let stdin = child.stdin.take().unwrap(); ``` to avoid partially moving the `child` and thus blocking yourself from calling functions on `child` while using `stdin`. `stdout: [Option](../option/enum.option "enum std::option::Option")<[ChildStdout](struct.childstdout "struct std::process::ChildStdout")>`The handle for reading from the child’s standard output (stdout), if it has been captured. You might find it helpful to do ⓘ ``` let stdout = child.stdout.take().unwrap(); ``` to avoid partially moving the `child` and thus blocking yourself from calling functions on `child` while using `stdout`. `stderr: [Option](../option/enum.option "enum std::option::Option")<[ChildStderr](struct.childstderr "struct std::process::ChildStderr")>`The handle for reading from the child’s standard error (stderr), if it has been captured. You might find it helpful to do ⓘ ``` let stderr = child.stderr.take().unwrap(); ``` to avoid partially moving the `child` and thus blocking yourself from calling functions on `child` while using `stderr`. Implementations --------------- [source](https://doc.rust-lang.org/src/std/process.rs.html#1833-2010)### impl Child [source](https://doc.rust-lang.org/src/std/process.rs.html#1859-1861)#### pub fn kill(&mut self) -> Result<()> Forces the child process to exit. If the child has already exited, an [`InvalidInput`](../io/enum.errorkind#variant.InvalidInput) error is returned. The mapping to [`ErrorKind`](../io/enum.errorkind)s is not part of the compatibility contract of the function. This is equivalent to sending a SIGKILL on Unix platforms. ##### Examples Basic usage: ``` use std::process::Command; let mut command = Command::new("yes"); if let Ok(mut child) = command.spawn() { child.kill().expect("command wasn't running"); } else { println!("yes command didn't start"); } ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1881-1883)1.3.0 · #### pub fn id(&self) -> u32 Returns the OS-assigned process identifier associated with this child. ##### Examples Basic usage: ``` use std::process::Command; let mut command = Command::new("ls"); if let Ok(child) = command.spawn() { println!("Child's ID is {}", child.id()); } else { println!("ls command didn't start"); } ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1910-1913)#### pub fn wait(&mut self) -> Result<ExitStatus> Waits for the child to exit completely, returning the status that it exited with. This function will continue to have the same return value after it has been called at least once. The stdin handle to the child process, if any, will be closed before waiting. This helps avoid deadlock: it ensures that the child does not block waiting for input from the parent, while the parent waits for the child to exit. ##### Examples Basic usage: ``` use std::process::Command; let mut command = Command::new("ls"); if let Ok(mut child) = command.spawn() { child.wait().expect("command wasn't running"); println!("Child has finished its execution!"); } else { println!("ls command didn't start"); } ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1950-1952)1.18.0 · #### pub fn try\_wait(&mut self) -> Result<Option<ExitStatus>> Attempts to collect the exit status of the child if it has already exited. This function will not block the calling thread and will only check to see if the child process has exited or not. If the child has exited then on Unix the process ID is reaped. This function is guaranteed to repeatedly return a successful exit status so long as the child has already exited. If the child has exited, then `Ok(Some(status))` is returned. If the exit status is not available at this time then `Ok(None)` is returned. If an error occurs, then that error is returned. Note that unlike `wait`, this function will not attempt to drop stdin. ##### Examples Basic usage: ``` use std::process::Command; let mut child = Command::new("ls").spawn().unwrap(); match child.try_wait() { Ok(Some(status)) => println!("exited with: {status}"), Ok(None) => { println!("status not ready yet, let's really wait"); let res = child.wait(); println!("result: {res:?}"); } Err(e) => println!("error attempting to wait: {e}"), } ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1987-2009)#### pub fn wait\_with\_output(self) -> Result<Output> Simultaneously waits for the child to exit and collect all remaining output on the stdout/stderr handles, returning an `Output` instance. The stdin handle to the child process, if any, will be closed before waiting. This helps avoid deadlock: it ensures that the child does not block waiting for input from the parent, while the parent waits for the child to exit. By default, stdin, stdout and stderr are inherited from the parent. In order to capture the output into this `Result<Output>` it is necessary to create new pipes between parent and child. Use `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively. ##### Examples ⓘ ``` use std::process::{Command, Stdio}; let child = Command::new("/bin/cat") .arg("file.txt") .stdout(Stdio::piped()) .spawn() .expect("failed to execute child"); let output = child .wait_with_output() .expect("failed to wait on child"); assert!(output.status.success()); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#43-48)1.63.0 · ### impl AsHandle for Child Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#45-47)#### fn as\_handle(&self) -> BorrowedHandle<'\_> Borrows the handle. [Read more](../os/windows/io/trait.ashandle#tymethod.as_handle) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#35-40)1.2.0 · ### impl AsRawHandle for Child Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#37-39)#### fn as\_raw\_handle(&self) -> RawHandle Extracts the raw handle. [Read more](../os/windows/io/trait.asrawhandle#tymethod.as_raw_handle) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#232-236)### impl ChildExt for Child Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#233-235)#### fn main\_thread\_handle(&self) -> BorrowedHandle<'\_> 🔬This is a nightly-only experimental API. (`windows_process_extensions_main_thread_handle` [#96723](https://github.com/rust-lang/rust/issues/96723)) Extracts the main thread raw handle, without taking ownership [source](https://doc.rust-lang.org/src/std/sys/unix/process/process_unix.rs.html#820-834)### impl ChildExt for Child [source](https://doc.rust-lang.org/src/std/sys/unix/process/process_unix.rs.html#821-826)#### fn pidfd(&self) -> Result<&PidFd> 🔬This is a nightly-only experimental API. (`linux_pidfd` [#82971](https://github.com/rust-lang/rust/issues/82971)) Available on **Linux** only.Obtains a reference to the [`PidFd`](../os/linux/process/struct.pidfd "PidFd") created for this [`Child`](struct.child), if available. [Read more](../os/linux/process/trait.childext#tymethod.pidfd) [source](https://doc.rust-lang.org/src/std/sys/unix/process/process_unix.rs.html#828-833)#### fn take\_pidfd(&mut self) -> Result<PidFd> 🔬This is a nightly-only experimental API. (`linux_pidfd` [#82971](https://github.com/rust-lang/rust/issues/82971)) Available on **Linux** only.Takes ownership of the [`PidFd`](../os/linux/process/struct.pidfd "PidFd") created for this [`Child`](struct.child), if available. [Read more](../os/linux/process/trait.childext#tymethod.take_pidfd) [source](https://doc.rust-lang.org/src/std/process.rs.html#237-245)1.16.0 · ### impl Debug for Child [source](https://doc.rust-lang.org/src/std/process.rs.html#238-244)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#58-62)1.63.0 · ### impl From<Child> for OwnedHandle Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#59-61)#### fn from(child: Child) -> OwnedHandle Converts to this type from the input type. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#51-55)1.4.0 · ### impl IntoRawHandle for Child Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#52-54)#### fn into\_raw\_handle(self) -> RawHandle Consumes this object, returning the raw underlying handle. [Read more](../os/windows/io/trait.intorawhandle#tymethod.into_raw_handle) Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for Child ### impl Send for Child ### impl Sync for Child ### impl Unpin for Child ### impl UnwindSafe for Child Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Struct std::process::ChildStderr Struct std::process::ChildStderr ================================ ``` pub struct ChildStderr { /* private fields */ } ``` A handle to a child process’s stderr. This struct is used in the [`stderr`](struct.child#structfield.stderr) field on [`Child`](struct.child "Child"). When an instance of `ChildStderr` is [dropped](../ops/trait.drop), the `ChildStderr`’s underlying file handle will be closed. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#446-451)1.63.0 · ### impl AsFd for ChildStderr Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#448-450)#### fn as\_fd(&self) -> BorrowedFd<'\_> Borrows the file descriptor. [Read more](../os/unix/io/trait.asfd#tymethod.as_fd) [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#547-552)1.63.0 · ### impl AsHandle for ChildStderr Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#549-551)#### fn as\_handle(&self) -> BorrowedHandle<'\_> Borrows the handle. [Read more](../os/windows/io/trait.ashandle#tymethod.as_handle) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#382-387)1.2.0 · ### impl AsRawFd for ChildStderr Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#384-386)#### fn as\_raw\_fd(&self) -> RawFd Extracts the raw file descriptor. [Read more](../os/unix/io/trait.asrawfd#tymethod.as_raw_fd) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#81-86)1.2.0 · ### impl AsRawHandle for ChildStderr Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#83-85)#### fn as\_raw\_handle(&self) -> RawHandle Extracts the raw handle. [Read more](../os/windows/io/trait.asrawhandle#tymethod.as_raw_handle) [source](https://doc.rust-lang.org/src/std/process.rs.html#447-451)1.16.0 · ### impl Debug for ChildStderr [source](https://doc.rust-lang.org/src/std/process.rs.html#448-450)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#454-459)1.63.0 · ### impl From<ChildStderr> for OwnedFd Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#456-458)#### fn from(child\_stderr: ChildStderr) -> OwnedFd Converts to this type from the input type. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#555-560)1.63.0 · ### impl From<ChildStderr> for OwnedHandle Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#557-559)#### fn from(child\_stderr: ChildStderr) -> OwnedHandle Converts to this type from the input type. [source](https://doc.rust-lang.org/src/std/process.rs.html#1366-1394)1.20.0 · ### impl From<ChildStderr> for Stdio [source](https://doc.rust-lang.org/src/std/process.rs.html#1391-1393)#### fn from(child: ChildStderr) -> Stdio Converts a [`ChildStderr`](struct.childstderr "ChildStderr") into a [`Stdio`](struct.stdio "Stdio"). ##### Examples ``` use std::process::{Command, Stdio}; let reverse = Command::new("rev") .arg("non_existing_file.txt") .stderr(Stdio::piped()) .spawn() .expect("failed reverse command"); let cat = Command::new("cat") .arg("-") .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here .output() .expect("failed echo command"); assert_eq!( String::from_utf8_lossy(&cat.stdout), "rev: cannot open non_existing_file.txt: No such file or directory\n" ); ``` [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#406-411)1.4.0 · ### impl IntoRawFd for ChildStderr Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#408-410)#### fn into\_raw\_fd(self) -> RawFd Consumes this object, returning the raw underlying file descriptor. [Read more](../os/unix/io/trait.intorawfd#tymethod.into_raw_fd) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#103-107)1.4.0 · ### impl IntoRawHandle for ChildStderr Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#104-106)#### fn into\_raw\_handle(self) -> RawHandle Consumes this object, returning the raw underlying handle. [Read more](../os/windows/io/trait.intorawhandle#tymethod.into_raw_handle) [source](https://doc.rust-lang.org/src/std/process.rs.html#413-426)### impl Read for ChildStderr [source](https://doc.rust-lang.org/src/std/process.rs.html#414-416)#### fn read(&mut self, buf: &mut [u8]) -> Result<usize> Pull some bytes from this source into the specified buffer, returning how many bytes were read. [Read more](../io/trait.read#tymethod.read) [source](https://doc.rust-lang.org/src/std/process.rs.html#418-420)#### fn read\_vectored(&mut self, bufs: &mut [IoSliceMut<'\_>]) -> Result<usize> Like `read`, except that it reads into a slice of buffers. [Read more](../io/trait.read#method.read_vectored) [source](https://doc.rust-lang.org/src/std/process.rs.html#423-425)#### fn is\_read\_vectored(&self) -> bool 🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941)) Determines if this `Read`er has an efficient `read_vectored` implementation. [Read more](../io/trait.read#method.is_read_vectored) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#706-708)#### fn read\_to\_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> Read all bytes until EOF in this source, placing them into `buf`. [Read more](../io/trait.read#method.read_to_end) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#749-751)#### fn read\_to\_string(&mut self, buf: &mut String) -> Result<usize> Read all bytes until EOF in this source, appending them to `buf`. [Read more](../io/trait.read#method.read_to_string) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#804-806)1.6.0 · #### fn read\_exact(&mut self, buf: &mut [u8]) -> Result<()> Read the exact number of bytes required to fill `buf`. [Read more](../io/trait.read#method.read_exact) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#815-817)#### fn read\_buf(&mut self, buf: BorrowedCursor<'\_>) -> Result<()> 🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485)) Pull some bytes from this source into the specified buffer. [Read more](../io/trait.read#method.read_buf) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#824-839)#### fn read\_buf\_exact(&mut self, cursor: BorrowedCursor<'\_>) -> Result<()> 🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485)) Read the exact number of bytes required to fill `cursor`. [Read more](../io/trait.read#method.read_buf_exact) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#876-881)#### fn by\_ref(&mut self) -> &mut Selfwhere Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Creates a “by reference” adaptor for this instance of `Read`. [Read more](../io/trait.read#method.by_ref) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#919-924)#### fn bytes(self) -> Bytes<Self>where Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Bytes](../io/struct.bytes "struct std::io::Bytes")<R> ``` impl<R: Read> Iterator for Bytes<R> type Item = Result<u8>; ``` Transforms this `Read` instance to an [`Iterator`](../iter/trait.iterator "Iterator") over its bytes. [Read more](../io/trait.read#method.bytes) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#957-962)#### fn chain<R: Read>(self, next: R) -> Chain<Self, R>where Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Chain](../io/struct.chain "struct std::io::Chain")<T, U> ``` impl<T: Read, U: Read> Read for Chain<T, U> ``` Creates an adapter which will chain this stream with another. [Read more](../io/trait.read#method.chain) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#996-1001)#### fn take(self, limit: u64) -> Take<Self>where Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Notable traits for [Take](../io/struct.take "struct std::io::Take")<T> ``` impl<T: Read> Read for Take<T> ``` Creates an adapter which will read at most `limit` bytes from it. [Read more](../io/trait.read#method.take) Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for ChildStderr ### impl Send for ChildStderr ### impl Sync for ChildStderr ### impl Unpin for ChildStderr ### impl UnwindSafe for ChildStderr Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::process::ExitStatusError Struct std::process::ExitStatusError ==================================== ``` pub struct ExitStatusError(_); ``` 🔬This is a nightly-only experimental API. (`exit_status_error` [#84908](https://github.com/rust-lang/rust/issues/84908)) Describes the result of a process after it has failed Produced by the [`.exit_ok`](struct.exitstatus#method.exit_ok) method on [`ExitStatus`](struct.exitstatus "ExitStatus"). Examples -------- ``` #![feature(exit_status_error)] use std::process::{Command, ExitStatusError}; fn run(cmd: &str) -> Result<(),ExitStatusError> { Command::new(cmd).status().unwrap().exit_ok()?; Ok(()) } run("true").unwrap(); run("false").unwrap_err(); ``` Implementations --------------- [source](https://doc.rust-lang.org/src/std/process.rs.html#1592-1658)### impl ExitStatusError [source](https://doc.rust-lang.org/src/std/process.rs.html#1624-1626)#### pub fn code(&self) -> Option<i32> 🔬This is a nightly-only experimental API. (`exit_status_error` [#84908](https://github.com/rust-lang/rust/issues/84908)) Reports the exit code, if applicable, from an `ExitStatusError`. In Unix terms the return value is the **exit status**: the value passed to `exit`, if the process finished by calling `exit`. Note that on Unix the exit status is truncated to 8 bits, and that values that didn’t come from a program’s call to `exit` may be invented by the runtime system (often, for example, 255, 254, 127 or 126). On Unix, this will return `None` if the process was terminated by a signal. If you want to handle such situations specially, consider using methods from [`ExitStatusExt`](../os/unix/process/trait.exitstatusext). If the process finished by calling `exit` with a nonzero value, this will return that exit status. If the error was something else, it will return `None`. If the process exited successfully (ie, by calling `exit(0)`), there is no `ExitStatusError`. So the return value from `ExitStatusError::code()` is always nonzero. ##### Examples ``` #![feature(exit_status_error)] use std::process::Command; let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err(); assert_eq!(bad.code(), Some(1)); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1649-1651)#### pub fn code\_nonzero(&self) -> Option<NonZeroI32> 🔬This is a nightly-only experimental API. (`exit_status_error` [#84908](https://github.com/rust-lang/rust/issues/84908)) Reports the exit code, if applicable, from an `ExitStatusError`, as a `NonZero` This is exactly like [`code()`](struct.exitstatuserror#method.code), except that it returns a `NonZeroI32`. Plain `code`, returning a plain integer, is provided because is is often more convenient. The returned value from `code()` is indeed also nonzero; use `code_nonzero()` when you want a type-level guarantee of nonzeroness. ##### Examples ``` #![feature(exit_status_error)] use std::num::NonZeroI32; use std::process::Command; let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err(); assert_eq!(bad.code_nonzero().unwrap(), NonZeroI32::try_from(1).unwrap()); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1655-1657)#### pub fn into\_status(&self) -> ExitStatus 🔬This is a nightly-only experimental API. (`exit_status_error` [#84908](https://github.com/rust-lang/rust/issues/84908)) Converts an `ExitStatusError` (back) to an `ExitStatus`. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/process.rs.html#1585)### impl Clone for ExitStatusError [source](https://doc.rust-lang.org/src/std/process.rs.html#1585)#### fn clone(&self) -> ExitStatusError Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)1.0.0 · #### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/process.rs.html#1585)### impl Debug for ExitStatusError [source](https://doc.rust-lang.org/src/std/process.rs.html#1585)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/process.rs.html#1668-1672)### impl Display for ExitStatusError [source](https://doc.rust-lang.org/src/std/process.rs.html#1669-1671)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/process.rs.html#1675)### impl Error for ExitStatusError [source](https://doc.rust-lang.org/src/core/error.rs.html#83)1.30.0 · #### fn source(&self) -> Option<&(dyn Error + 'static)> The lower-level source of this error, if any. [Read more](../error/trait.error#method.source) [source](https://doc.rust-lang.org/src/core/error.rs.html#109)1.0.0 · #### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to\_string() [Read more](../error/trait.error#method.description) [source](https://doc.rust-lang.org/src/core/error.rs.html#119)1.0.0 · #### fn cause(&self) -> Option<&dyn Error> 👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting [source](https://doc.rust-lang.org/src/core/error.rs.html#193)#### fn provide(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access` [#99301](https://github.com/rust-lang/rust/issues/99301)) Provides type based access to context intended for error reports. [Read more](../error/trait.error#method.provide) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#317-343)### impl ExitStatusExt for ExitStatusError Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#318-322)#### fn from\_raw(raw: i32) -> Self Creates a new `ExitStatus` or `ExitStatusError` from the raw underlying integer status value from `wait` [Read more](../os/unix/process/trait.exitstatusext#tymethod.from_raw) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#324-326)#### fn signal(&self) -> Option<i32> If the process was terminated by a signal, returns that signal. [Read more](../os/unix/process/trait.exitstatusext#tymethod.signal) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#328-330)#### fn core\_dumped(&self) -> bool If the process was terminated by a signal, says whether it dumped core. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#332-334)#### fn stopped\_signal(&self) -> Option<i32> If the process was stopped by a signal, returns that signal. [Read more](../os/unix/process/trait.exitstatusext#tymethod.stopped_signal) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#336-338)#### fn continued(&self) -> bool Whether the process was continued from a stopped status. [Read more](../os/unix/process/trait.exitstatusext#tymethod.continued) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#340-342)#### fn into\_raw(self) -> i32 Returns the underlying raw `wait` status. [Read more](../os/unix/process/trait.exitstatusext#tymethod.into_raw) [source](https://doc.rust-lang.org/src/std/process.rs.html#1661-1665)### impl Into<ExitStatus> for ExitStatusError [source](https://doc.rust-lang.org/src/std/process.rs.html#1662-1664)#### fn into(self) -> ExitStatus Converts this type into the (usually inferred) input type. [source](https://doc.rust-lang.org/src/std/process.rs.html#1585)### impl PartialEq<ExitStatusError> for ExitStatusError [source](https://doc.rust-lang.org/src/std/process.rs.html#1585)#### fn eq(&self, other: &ExitStatusError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)1.0.0 · #### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/std/process.rs.html#1585)### impl Copy for ExitStatusError [source](https://doc.rust-lang.org/src/std/process.rs.html#1585)### impl Eq for ExitStatusError [source](https://doc.rust-lang.org/src/std/process.rs.html#1585)### impl StructuralEq for ExitStatusError [source](https://doc.rust-lang.org/src/std/process.rs.html#1585)### impl StructuralPartialEq for ExitStatusError Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for ExitStatusError ### impl Send for ExitStatusError ### impl Sync for ExitStatusError ### impl Unpin for ExitStatusError ### impl UnwindSafe for ExitStatusError Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/error.rs.html#197)### impl<E> Provider for Ewhere E: [Error](../error/trait.error "trait std::error::Error") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/error.rs.html#201)#### fn provide(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`provide_any` [#96024](https://github.com/rust-lang/rust/issues/96024)) Data providers should implement this method to provide *all* values they are able to provide by using `demand`. [Read more](../any/trait.provider#tymethod.provide) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2500)### impl<T> ToString for Twhere T: [Display](../fmt/trait.display "trait std::fmt::Display") + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/alloc/string.rs.html#2506)#### default fn to\_string(&self) -> String Converts the given value to a `String`. [Read more](../string/trait.tostring#tymethod.to_string) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Trait std::process::Termination Trait std::process::Termination =============================== ``` pub trait Termination { fn report(self) -> ExitCode; } ``` A trait for implementing arbitrary return types in the `main` function. The C-main function only supports returning integers. So, every type implementing the `Termination` trait has to be converted to an integer. The default implementations are returning `libc::EXIT_SUCCESS` to indicate a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned. Because different runtimes have different specifications on the return value of the `main` function, this trait is likely to be available only on standard library’s runtime for convenience. Other runtimes are not required to provide similar functionality. Required Methods ---------------- [source](https://doc.rust-lang.org/src/std/process.rs.html#2164)#### fn report(self) -> ExitCode Is called to get the representation of the value as status code. This status code is returned to the operating system. Implementors ------------ [source](https://doc.rust-lang.org/src/std/process.rs.html#2183-2187)### impl Termination for Infallible [source](https://doc.rust-lang.org/src/std/process.rs.html#2176-2180)### impl Termination for ! [source](https://doc.rust-lang.org/src/std/process.rs.html#2168-2173)### impl Termination for () [source](https://doc.rust-lang.org/src/std/process.rs.html#2190-2195)### impl Termination for ExitCode [source](https://doc.rust-lang.org/src/std/process.rs.html#2198-2210)### impl<T: Termination, E: Debug> Termination for Result<T, E> rust Struct std::process::Command Struct std::process::Command ============================ ``` pub struct Command { /* private fields */ } ``` A process builder, providing fine-grained control over how a new process should be spawned. A default configuration can be generated using `Command::new(program)`, where `program` gives a path to the program to be executed. Additional builder methods allow the configuration to be changed (for example, by adding arguments) prior to spawning: ``` use std::process::Command; let output = if cfg!(target_os = "windows") { Command::new("cmd") .args(["/C", "echo hello"]) .output() .expect("failed to execute process") } else { Command::new("sh") .arg("-c") .arg("echo hello") .output() .expect("failed to execute process") }; let hello = output.stdout; ``` `Command` can be reused to spawn multiple processes. The builder methods change the command without needing to immediately spawn the process. ``` use std::process::Command; let mut echo_hello = Command::new("sh"); echo_hello.arg("-c") .arg("echo hello"); let hello_1 = echo_hello.output().expect("failed to execute process"); let hello_2 = echo_hello.output().expect("failed to execute process"); ``` Similarly, you can call builder methods after spawning a process and then spawn a new process with the modified settings. ``` use std::process::Command; let mut list_dir = Command::new("ls"); // Execute `ls` in the current directory of the program. list_dir.status().expect("process failed to execute"); println!(); // Change `ls` to execute in the root directory. list_dir.current_dir("/"); // And then execute `ls` again but in the root directory. list_dir.status().expect("process failed to execute"); ``` Implementations --------------- [source](https://doc.rust-lang.org/src/std/process.rs.html#521-1032)### impl Command [source](https://doc.rust-lang.org/src/std/process.rs.html#557-559)#### pub fn new<S: AsRef<OsStr>>(program: S) -> Command Constructs a new `Command` for launching the program at path `program`, with the following default configuration: * No arguments to the program * Inherit the current process’s environment * Inherit the current process’s working directory * Inherit stdin/stdout/stderr for [`spawn`](struct.command#method.spawn) or [`status`](struct.command#method.status), but create pipes for [`output`](struct.command#method.output) Builder methods are provided to change these defaults and otherwise configure the process. If `program` is not an absolute path, the `PATH` will be searched in an OS-defined way. The search path to be used may be controlled by setting the `PATH` environment variable on the Command, but this has some implementation limitations on Windows (see issue #37519). ##### Examples Basic usage: ``` use std::process::Command; Command::new("sh") .spawn() .expect("sh command failed to start"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#603-606)#### pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command Adds an argument to pass to the program. Only one argument can be passed per use. So instead of: ``` .arg("-C /path/to/repo") ``` usage would be: ``` .arg("-C") .arg("/path/to/repo") ``` To pass multiple arguments see [`args`](struct.command#method.args). Note that the argument is not passed through a shell, but given literally to the program. This means that shell syntax like quotes, escaped characters, word splitting, glob patterns, substitution, etc. have no effect. ##### Examples Basic usage: ``` use std::process::Command; Command::new("ls") .arg("-l") .arg("-a") .spawn() .expect("ls command failed to start"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#632-641)#### pub fn args<I, S>(&mut self, args: I) -> &mut Commandwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = S>, S: [AsRef](../convert/trait.asref "trait std::convert::AsRef")<[OsStr](../ffi/struct.osstr "struct std::ffi::OsStr")>, Adds multiple arguments to pass to the program. To pass a single argument see [`arg`](struct.command#method.arg). Note that the arguments are not passed through a shell, but given literally to the program. This means that shell syntax like quotes, escaped characters, word splitting, glob patterns, substitution, etc. have no effect. ##### Examples Basic usage: ``` use std::process::Command; Command::new("ls") .args(["-l", "-a"]) .spawn() .expect("ls command failed to start"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#661-668)#### pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Commandwhere K: [AsRef](../convert/trait.asref "trait std::convert::AsRef")<[OsStr](../ffi/struct.osstr "struct std::ffi::OsStr")>, V: [AsRef](../convert/trait.asref "trait std::convert::AsRef")<[OsStr](../ffi/struct.osstr "struct std::ffi::OsStr")>, Inserts or updates an environment variable mapping. Note that environment variable names are case-insensitive (but case-preserving) on Windows, and case-sensitive on all other platforms. ##### Examples Basic usage: ``` use std::process::Command; Command::new("ls") .env("PATH", "/bin") .spawn() .expect("ls command failed to start"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#695-705)1.19.0 · #### pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Commandwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = [(K, V)](../primitive.tuple)>, K: [AsRef](../convert/trait.asref "trait std::convert::AsRef")<[OsStr](../ffi/struct.osstr "struct std::ffi::OsStr")>, V: [AsRef](../convert/trait.asref "trait std::convert::AsRef")<[OsStr](../ffi/struct.osstr "struct std::ffi::OsStr")>, Adds or updates multiple environment variable mappings. ##### Examples Basic usage: ``` use std::process::{Command, Stdio}; use std::env; use std::collections::HashMap; let filtered_env : HashMap<String, String> = env::vars().filter(|&(ref k, _)| k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH" ).collect(); Command::new("printenv") .stdin(Stdio::null()) .stdout(Stdio::inherit()) .env_clear() .envs(&filtered_env) .spawn() .expect("printenv failed to start"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#722-725)#### pub fn env\_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command Removes an environment variable mapping. ##### Examples Basic usage: ``` use std::process::Command; Command::new("ls") .env_remove("PATH") .spawn() .expect("ls command failed to start"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#742-745)#### pub fn env\_clear(&mut self) -> &mut Command Clears the entire environment map for the child process. ##### Examples Basic usage: ``` use std::process::Command; Command::new("ls") .env_clear() .spawn() .expect("ls command failed to start"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#772-775)#### pub fn current\_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command Sets the working directory for the child process. ##### Platform-specific behavior If the program path is relative (e.g., `"./script.sh"`), it’s ambiguous whether it should be interpreted relative to the parent’s working directory or relative to `current_dir`. The behavior in this case is platform specific and unstable, and it’s recommended to use [`canonicalize`](../fs/fn.canonicalize) to get an absolute program path instead. ##### Examples Basic usage: ``` use std::process::Command; Command::new("ls") .current_dir("/bin") .spawn() .expect("ls command failed to start"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#801-804)#### pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command Configuration for the child process’s standard input (stdin) handle. Defaults to [`inherit`](struct.stdio#method.inherit) when used with [`spawn`](struct.command#method.spawn) or [`status`](struct.command#method.status), and defaults to [`piped`](struct.stdio#method.piped) when used with [`output`](struct.command#method.output). ##### Examples Basic usage: ``` use std::process::{Command, Stdio}; Command::new("ls") .stdin(Stdio::null()) .spawn() .expect("ls command failed to start"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#830-833)#### pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command Configuration for the child process’s standard output (stdout) handle. Defaults to [`inherit`](struct.stdio#method.inherit) when used with [`spawn`](struct.command#method.spawn) or [`status`](struct.command#method.status), and defaults to [`piped`](struct.stdio#method.piped) when used with [`output`](struct.command#method.output). ##### Examples Basic usage: ``` use std::process::{Command, Stdio}; Command::new("ls") .stdout(Stdio::null()) .spawn() .expect("ls command failed to start"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#859-862)#### pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command Configuration for the child process’s standard error (stderr) handle. Defaults to [`inherit`](struct.stdio#method.inherit) when used with [`spawn`](struct.command#method.spawn) or [`status`](struct.command#method.status), and defaults to [`piped`](struct.stdio#method.piped) when used with [`output`](struct.command#method.output). ##### Examples Basic usage: ``` use std::process::{Command, Stdio}; Command::new("ls") .stderr(Stdio::null()) .spawn() .expect("ls command failed to start"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#880-882)#### pub fn spawn(&mut self) -> Result<Child> Executes the command as a child process, returning a handle to it. By default, stdin, stdout and stderr are inherited from the parent. ##### Examples Basic usage: ``` use std::process::Command; Command::new("ls") .spawn() .expect("ls command failed to start"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#909-914)#### pub fn output(&mut self) -> Result<Output> Executes the command as a child process, waiting for it to finish and collecting all of its output. By default, stdout and stderr are captured (and used to provide the resulting output). Stdin is not inherited from the parent and any attempt by the child process to read from the stdin stream will result in the stream immediately closing. ##### Examples ⓘ ``` use std::process::Command; use std::io::{self, Write}; let output = Command::new("/bin/cat") .arg("file.txt") .output() .expect("failed to execute process"); println!("status: {}", output.status); io::stdout().write_all(&output.stdout).unwrap(); io::stderr().write_all(&output.stderr).unwrap(); assert!(output.status.success()); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#936-941)#### pub fn status(&mut self) -> Result<ExitStatus> Executes a command as a child process, waiting for it to finish and collecting its status. By default, stdin, stdout and stderr are inherited from the parent. ##### Examples ⓘ ``` use std::process::Command; let status = Command::new("/bin/cat") .arg("file.txt") .status() .expect("failed to execute process"); println!("process finished with: {status}"); assert!(status.success()); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#955-957)1.57.0 · #### pub fn get\_program(&self) -> &OsStr Returns the path to the program that was given to [`Command::new`](struct.command#method.new "Command::new"). ##### Examples ``` use std::process::Command; let cmd = Command::new("echo"); assert_eq!(cmd.get_program(), "echo"); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#977-979)1.57.0 · #### pub fn get\_args(&self) -> CommandArgs<'\_> Notable traits for [CommandArgs](struct.commandargs "struct std::process::CommandArgs")<'a> ``` impl<'a> Iterator for CommandArgs<'a> type Item = &'a OsStr; ``` Returns an iterator of the arguments that will be passed to the program. This does not include the path to the program as the first argument; it only includes the arguments specified with [`Command::arg`](struct.command#method.arg "Command::arg") and [`Command::args`](struct.command#method.args "Command::args"). ##### Examples ``` use std::ffi::OsStr; use std::process::Command; let mut cmd = Command::new("echo"); cmd.arg("first").arg("second"); let args: Vec<&OsStr> = cmd.get_args().collect(); assert_eq!(args, &["first", "second"]); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1008-1010)1.57.0 · #### pub fn get\_envs(&self) -> CommandEnvs<'\_> Notable traits for [CommandEnvs](struct.commandenvs "struct std::process::CommandEnvs")<'a> ``` impl<'a> Iterator for CommandEnvs<'a> type Item = (&'a OsStr, Option<&'a OsStr>); ``` Returns an iterator of the environment variables that will be set when the process is spawned. Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first value is the key, and the second is the value, which is [`None`](../option/enum.option#variant.None "None") if the environment variable is to be explicitly removed. This only includes environment variables explicitly set with [`Command::env`](struct.command#method.env "Command::env"), [`Command::envs`](struct.command#method.envs "Command::envs"), and [`Command::env_remove`](struct.command#method.env_remove "Command::env_remove"). It does not include environment variables that will be inherited by the child process. ##### Examples ``` use std::ffi::OsStr; use std::process::Command; let mut cmd = Command::new("ls"); cmd.env("TERM", "dumb").env_remove("TZ"); let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect(); assert_eq!(envs, &[ (OsStr::new("TERM"), Some(OsStr::new("dumb"))), (OsStr::new("TZ"), None) ]); ``` [source](https://doc.rust-lang.org/src/std/process.rs.html#1029-1031)1.57.0 · #### pub fn get\_current\_dir(&self) -> Option<&Path> Returns the working directory for the child process. This returns [`None`](../option/enum.option#variant.None "None") if the working directory will not be changed. ##### Examples ``` use std::path::Path; use std::process::Command; let mut cmd = Command::new("ls"); assert_eq!(cmd.get_current_dir(), None); cmd.current_dir("/bin"); assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin"))); ``` Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#185-227)### impl CommandExt for Command Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#186-189)#### fn uid(&mut self, id: u32) -> &mut Command Sets the child process’s user ID. This translates to a `setuid` call in the child process. Failure in the `setuid` call will cause the spawn to fail. [Read more](../os/unix/process/trait.commandext#tymethod.uid) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#191-194)#### fn gid(&mut self, id: u32) -> &mut Command Similar to `uid`, but sets the group ID of the child process. This has the same semantics as the `uid` field. [Read more](../os/unix/process/trait.commandext#tymethod.gid) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#196-199)#### fn groups(&mut self, groups: &[u32]) -> &mut Command 🔬This is a nightly-only experimental API. (`setgroups` [#90747](https://github.com/rust-lang/rust/issues/90747)) Sets the supplementary group IDs for the calling process. Translates to a `setgroups` call in the child process. [Read more](../os/unix/process/trait.commandext#tymethod.groups) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#201-207)#### unsafe fn pre\_exec<F>(&mut self, f: F) -> &mut Commandwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> [Result](../io/type.result "type std::io::Result")<[()](../primitive.unit)> + [Send](../marker/trait.send "trait std::marker::Send") + [Sync](../marker/trait.sync "trait std::marker::Sync") + 'static, Schedules a closure to be run just before the `exec` function is invoked. [Read more](../os/unix/process/trait.commandext#tymethod.pre_exec) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#209-213)#### fn exec(&mut self) -> Error Performs all the required setup by this `Command`, followed by calling the `execvp` syscall. [Read more](../os/unix/process/trait.commandext#tymethod.exec) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#215-221)#### fn arg0<S>(&mut self, arg: S) -> &mut Commandwhere S: [AsRef](../convert/trait.asref "trait std::convert::AsRef")<[OsStr](../ffi/struct.osstr "struct std::ffi::OsStr")>, Set executable argument [Read more](../os/unix/process/trait.commandext#tymethod.arg0) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#223-226)#### fn process\_group(&mut self, pgroup: i32) -> &mut Command Sets the process group ID (PGID) of the child process. Equivalent to a `setpgid` call in the child process, but may be more efficient. [Read more](../os/unix/process/trait.commandext#tymethod.process_group) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#105-110)1.15.0 · #### fn before\_exec<F>(&mut self, f: F) -> &mut Commandwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> [Result](../io/type.result "type std::io::Result")<[()](../primitive.unit)> + [Send](../marker/trait.send "trait std::marker::Send") + [Sync](../marker/trait.sync "trait std::marker::Sync") + 'static, 👎Deprecated since 1.37.0: should be unsafe, use `pre_exec` instead Schedules a closure to be run just before the `exec` function is invoked. [Read more](../os/unix/process/trait.commandext#method.before_exec) [source](https://doc.rust-lang.org/src/std/os/linux/process.rs.html#160-165)### impl CommandExt for Command Available on **Linux** only. [source](https://doc.rust-lang.org/src/std/os/linux/process.rs.html#161-164)#### fn create\_pidfd(&mut self, val: bool) -> &mut Command 🔬This is a nightly-only experimental API. (`linux_pidfd` [#82971](https://github.com/rust-lang/rust/issues/82971)) Sets whether a [`PidFd`](../os/linux/process/struct.pidfd) should be created for the [`Child`](struct.child) spawned by this [`Command`](struct.command). By default, no pidfd will be created. [Read more](../os/linux/process/trait.commandext#tymethod.create_pidfd) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#198-222)1.16.0 · ### impl CommandExt for Command Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#199-202)#### fn creation\_flags(&mut self, flags: u32) -> &mut Command Sets the [process creation flags](https://docs.microsoft.com/en-us/windows/win32/procthread/process-creation-flags) to be passed to `CreateProcess`. [Read more](../os/windows/process/trait.commandext#tymethod.creation_flags) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#204-207)#### fn force\_quotes(&mut self, enabled: bool) -> &mut Command 🔬This is a nightly-only experimental API. (`windows_process_extensions_force_quotes` [#82227](https://github.com/rust-lang/rust/issues/82227)) Forces all arguments to be wrapped in quote (`"`) characters. [Read more](../os/windows/process/trait.commandext#tymethod.force_quotes) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#209-212)#### fn raw\_arg<S: AsRef<OsStr>>(&mut self, raw\_text: S) -> &mut Command Append literal text to the command line without any quoting or escaping. [Read more](../os/windows/process/trait.commandext#tymethod.raw_arg) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#214-221)#### fn async\_pipes(&mut self, always\_async: bool) -> &mut Command 🔬This is a nightly-only experimental API. (`windows_process_extensions_async_pipes` [#98289](https://github.com/rust-lang/rust/issues/98289)) When [`process::Command`](struct.command "process::Command") creates pipes, request that our side is always async. [Read more](../os/windows/process/trait.commandext#tymethod.async_pipes) [source](https://doc.rust-lang.org/src/std/process.rs.html#1035-1042)### impl Debug for Command [source](https://doc.rust-lang.org/src/std/process.rs.html#1039-1041)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Format the program and arguments of a Command for display. Any non-utf8 data is lossily converted using the utf8 replacement character. Auto Trait Implementations -------------------------- ### impl !RefUnwindSafe for Command ### impl Send for Command ### impl Sync for Command ### impl Unpin for Command ### impl !UnwindSafe for Command Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::process::CommandArgs Struct std::process::CommandArgs ================================ ``` pub struct CommandArgs<'a> { /* private fields */ } ``` An iterator over the command arguments. This struct is created by [`Command::get_args`](struct.command#method.get_args "Command::get_args"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/process.rs.html#1062)### impl<'a> Debug for CommandArgs<'a> [source](https://doc.rust-lang.org/src/std/process.rs.html#1062)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/process.rs.html#1079-1086)### impl<'a> ExactSizeIterator for CommandArgs<'a> [source](https://doc.rust-lang.org/src/std/process.rs.html#1080-1082)#### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/std/process.rs.html#1083-1085)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/std/process.rs.html#1068-1076)### impl<'a> Iterator for CommandArgs<'a> #### type Item = &'a OsStr The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/std/process.rs.html#1070-1072)#### fn next(&mut self) -> Option<&'a OsStr> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/std/process.rs.html#1073-1075)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)#### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for CommandArgs<'a> ### impl<'a> Send for CommandArgs<'a> ### impl<'a> Sync for CommandArgs<'a> ### impl<'a> Unpin for CommandArgs<'a> ### impl<'a> UnwindSafe for CommandArgs<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Function std::process::id Function std::process::id ========================= ``` pub fn id() -> u32 ``` Returns the OS-assigned process identifier associated with this process. Examples -------- Basic usage: ``` use std::process; println!("My pid is {}", process::id()); ``` rust Struct std::process::Output Struct std::process::Output =========================== ``` pub struct Output { pub status: ExitStatus, pub stdout: Vec<u8>, pub stderr: Vec<u8>, } ``` The output of a finished process. This is returned in a Result by either the [`output`](struct.command#method.output) method of a [`Command`](struct.command "Command"), or the [`wait_with_output`](struct.child#method.wait_with_output) method of a [`Child`](struct.child "Child") process. Fields ------ `status: [ExitStatus](struct.exitstatus "struct std::process::ExitStatus")`The status (exit code) of the process. `stdout: [Vec](../vec/struct.vec "struct std::vec::Vec")<[u8](../primitive.u8)>`The data that the process wrote to stdout. `stderr: [Vec](../vec/struct.vec "struct std::vec::Vec")<[u8](../primitive.u8)>`The data that the process wrote to stderr. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/process.rs.html#1096)### impl Clone for Output [source](https://doc.rust-lang.org/src/std/process.rs.html#1096)#### fn clone(&self) -> Output Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone) [source](https://doc.rust-lang.org/src/core/clone.rs.html#132-134)#### fn clone\_from(&mut self, source: &Self) Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from) [source](https://doc.rust-lang.org/src/std/process.rs.html#1113-1133)1.7.0 · ### impl Debug for Output [source](https://doc.rust-lang.org/src/std/process.rs.html#1114-1132)#### fn fmt(&self, fmt: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/process.rs.html#1096)### impl PartialEq<Output> for Output [source](https://doc.rust-lang.org/src/std/process.rs.html#1096)#### fn eq(&self, other: &Output) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. [Read more](../cmp/trait.partialeq#tymethod.eq) [source](https://doc.rust-lang.org/src/core/cmp.rs.html#236)#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. [Read more](../cmp/trait.partialeq#method.ne) [source](https://doc.rust-lang.org/src/std/process.rs.html#1096)### impl Eq for Output [source](https://doc.rust-lang.org/src/std/process.rs.html#1096)### impl StructuralEq for Output [source](https://doc.rust-lang.org/src/std/process.rs.html#1096)### impl StructuralPartialEq for Output Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for Output ### impl Send for Output ### impl Sync for Output ### impl Unpin for Output ### impl UnwindSafe for Output Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#83)### impl<T> ToOwned for Twhere T: [Clone](../clone/trait.clone "trait std::clone::Clone"), #### type Owned = T The resulting type after obtaining ownership. [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#88)#### fn to\_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned) [source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#92)#### fn clone\_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion. rust Struct std::process::ChildStdin Struct std::process::ChildStdin =============================== ``` pub struct ChildStdin { /* private fields */ } ``` A handle to a child process’s standard input (stdin). This struct is used in the [`stdin`](struct.child#structfield.stdin) field on [`Child`](struct.child "Child"). When an instance of `ChildStdin` is [dropped](../ops/trait.drop), the `ChildStdin`’s underlying file handle will be closed. If the child process was blocked on input prior to being dropped, it will become unblocked after dropping. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#414-419)1.63.0 · ### impl AsFd for ChildStdin Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#416-418)#### fn as\_fd(&self) -> BorrowedFd<'\_> Borrows the file descriptor. [Read more](../os/unix/io/trait.asfd#tymethod.as_fd) [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#515-520)1.63.0 · ### impl AsHandle for ChildStdin Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#517-519)#### fn as\_handle(&self) -> BorrowedHandle<'\_> Borrows the handle. [Read more](../os/windows/io/trait.ashandle#tymethod.as_handle) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#366-371)1.2.0 · ### impl AsRawFd for ChildStdin Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#368-370)#### fn as\_raw\_fd(&self) -> RawFd Extracts the raw file descriptor. [Read more](../os/unix/io/trait.asrawfd#tymethod.as_raw_fd) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#65-70)1.2.0 · ### impl AsRawHandle for ChildStdin Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#67-69)#### fn as\_raw\_handle(&self) -> RawHandle Extracts the raw handle. [Read more](../os/windows/io/trait.asrawhandle#tymethod.as_raw_handle) [source](https://doc.rust-lang.org/src/std/process.rs.html#325-329)1.16.0 · ### impl Debug for ChildStdin [source](https://doc.rust-lang.org/src/std/process.rs.html#326-328)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#422-427)1.63.0 · ### impl From<ChildStdin> for OwnedFd Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#424-426)#### fn from(child\_stdin: ChildStdin) -> OwnedFd Converts to this type from the input type. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#523-528)1.63.0 · ### impl From<ChildStdin> for OwnedHandle Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#525-527)#### fn from(child\_stdin: ChildStdin) -> OwnedHandle Converts to this type from the input type. [source](https://doc.rust-lang.org/src/std/process.rs.html#1308-1334)1.20.0 · ### impl From<ChildStdin> for Stdio [source](https://doc.rust-lang.org/src/std/process.rs.html#1331-1333)#### fn from(child: ChildStdin) -> Stdio Converts a [`ChildStdin`](struct.childstdin "ChildStdin") into a [`Stdio`](struct.stdio "Stdio"). ##### Examples `ChildStdin` will be converted to `Stdio` using `Stdio::from` under the hood. ``` use std::process::{Command, Stdio}; let reverse = Command::new("rev") .stdin(Stdio::piped()) .spawn() .expect("failed reverse command"); let _echo = Command::new("echo") .arg("Hello, world!") .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here .output() .expect("failed echo command"); // "!dlrow ,olleH" echoed to console ``` [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#390-395)1.4.0 · ### impl IntoRawFd for ChildStdin Available on **Unix** only. [source](https://doc.rust-lang.org/src/std/os/unix/process.rs.html#392-394)#### fn into\_raw\_fd(self) -> RawFd Consumes this object, returning the raw underlying file descriptor. [Read more](../os/unix/io/trait.intorawfd#tymethod.into_raw_fd) [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#89-93)1.4.0 · ### impl IntoRawHandle for ChildStdin Available on **Windows** only. [source](https://doc.rust-lang.org/src/std/os/windows/process.rs.html#90-92)#### fn into\_raw\_handle(self) -> RawHandle Consumes this object, returning the raw underlying handle. [Read more](../os/windows/io/trait.intorawhandle#tymethod.into_raw_handle) [source](https://doc.rust-lang.org/src/std/process.rs.html#288-304)1.48.0 · ### impl Write for &ChildStdin [source](https://doc.rust-lang.org/src/std/process.rs.html#289-291)#### fn write(&mut self, buf: &[u8]) -> Result<usize> Write a buffer into this writer, returning how many bytes were written. [Read more](../io/trait.write#tymethod.write) [source](https://doc.rust-lang.org/src/std/process.rs.html#293-295)#### fn write\_vectored(&mut self, bufs: &[IoSlice<'\_>]) -> Result<usize> Like [`write`](../io/trait.write#tymethod.write), except that it writes from a slice of buffers. [Read more](../io/trait.write#method.write_vectored) [source](https://doc.rust-lang.org/src/std/process.rs.html#297-299)#### fn is\_write\_vectored(&self) -> bool 🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941)) Determines if this `Write`r has an efficient [`write_vectored`](../io/trait.write#method.write_vectored) implementation. [Read more](../io/trait.write#method.is_write_vectored) [source](https://doc.rust-lang.org/src/std/process.rs.html#301-303)#### fn flush(&mut self) -> Result<()> Flush this output stream, ensuring that all intermediately buffered contents reach their destination. [Read more](../io/trait.write#tymethod.flush) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1537-1552)#### fn write\_all(&mut self, buf: &[u8]) -> Result<()> Attempts to write an entire buffer into this writer. [Read more](../io/trait.write#method.write_all) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1602-1620)#### fn write\_all\_vectored(&mut self, bufs: &mut [IoSlice<'\_>]) -> Result<()> 🔬This is a nightly-only experimental API. (`write_all_vectored` [#70436](https://github.com/rust-lang/rust/issues/70436)) Attempts to write multiple buffers into this writer. [Read more](../io/trait.write#method.write_all_vectored) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1658-1690)#### fn write\_fmt(&mut self, fmt: Arguments<'\_>) -> Result<()> Writes a formatted string into this writer, returning any error encountered. [Read more](../io/trait.write#method.write_fmt) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1714-1719)#### fn by\_ref(&mut self) -> &mut Selfwhere Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Creates a “by reference” adapter for this instance of `Write`. [Read more](../io/trait.write#method.by_ref) [source](https://doc.rust-lang.org/src/std/process.rs.html#269-285)### impl Write for ChildStdin [source](https://doc.rust-lang.org/src/std/process.rs.html#270-272)#### fn write(&mut self, buf: &[u8]) -> Result<usize> Write a buffer into this writer, returning how many bytes were written. [Read more](../io/trait.write#tymethod.write) [source](https://doc.rust-lang.org/src/std/process.rs.html#274-276)#### fn write\_vectored(&mut self, bufs: &[IoSlice<'\_>]) -> Result<usize> Like [`write`](../io/trait.write#tymethod.write), except that it writes from a slice of buffers. [Read more](../io/trait.write#method.write_vectored) [source](https://doc.rust-lang.org/src/std/process.rs.html#278-280)#### fn is\_write\_vectored(&self) -> bool 🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941)) Determines if this `Write`r has an efficient [`write_vectored`](../io/trait.write#method.write_vectored) implementation. [Read more](../io/trait.write#method.is_write_vectored) [source](https://doc.rust-lang.org/src/std/process.rs.html#282-284)#### fn flush(&mut self) -> Result<()> Flush this output stream, ensuring that all intermediately buffered contents reach their destination. [Read more](../io/trait.write#tymethod.flush) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1537-1552)#### fn write\_all(&mut self, buf: &[u8]) -> Result<()> Attempts to write an entire buffer into this writer. [Read more](../io/trait.write#method.write_all) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1602-1620)#### fn write\_all\_vectored(&mut self, bufs: &mut [IoSlice<'\_>]) -> Result<()> 🔬This is a nightly-only experimental API. (`write_all_vectored` [#70436](https://github.com/rust-lang/rust/issues/70436)) Attempts to write multiple buffers into this writer. [Read more](../io/trait.write#method.write_all_vectored) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1658-1690)#### fn write\_fmt(&mut self, fmt: Arguments<'\_>) -> Result<()> Writes a formatted string into this writer, returning any error encountered. [Read more](../io/trait.write#method.write_fmt) [source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1714-1719)#### fn by\_ref(&mut self) -> &mut Selfwhere Self: [Sized](../marker/trait.sized "trait std::marker::Sized"), Creates a “by reference” adapter for this instance of `Write`. [Read more](../io/trait.write#method.by_ref) Auto Trait Implementations -------------------------- ### impl RefUnwindSafe for ChildStdin ### impl Send for ChildStdin ### impl Sync for ChildStdin ### impl Unpin for ChildStdin ### impl UnwindSafe for ChildStdin Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Struct std::process::CommandEnvs Struct std::process::CommandEnvs ================================ ``` pub struct CommandEnvs<'a> { /* private fields */ } ``` An iterator over the command environment variables. This struct is created by [`Command::get_envs`](struct.command#method.get_envs "crate::process::Command::get_envs"). See its documentation for more. Trait Implementations --------------------- [source](https://doc.rust-lang.org/src/std/sys_common/process.rs.html#95)### impl<'a> Debug for CommandEnvs<'a> [source](https://doc.rust-lang.org/src/std/sys_common/process.rs.html#95)#### fn fmt(&self, f: &mut Formatter<'\_>) -> Result Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt) [source](https://doc.rust-lang.org/src/std/sys_common/process.rs.html#112-119)### impl<'a> ExactSizeIterator for CommandEnvs<'a> [source](https://doc.rust-lang.org/src/std/sys_common/process.rs.html#113-115)#### fn len(&self) -> usize Returns the exact remaining length of the iterator. [Read more](../iter/trait.exactsizeiterator#method.len) [source](https://doc.rust-lang.org/src/std/sys_common/process.rs.html#116-118)#### fn is\_empty(&self) -> bool 🔬This is a nightly-only experimental API. (`exact_size_is_empty` [#35428](https://github.com/rust-lang/rust/issues/35428)) Returns `true` if the iterator is empty. [Read more](../iter/trait.exactsizeiterator#method.is_empty) [source](https://doc.rust-lang.org/src/std/sys_common/process.rs.html#101-109)### impl<'a> Iterator for CommandEnvs<'a> #### type Item = (&'a OsStr, Option<&'a OsStr>) The type of the elements being iterated over. [source](https://doc.rust-lang.org/src/std/sys_common/process.rs.html#103-105)#### fn next(&mut self) -> Option<Self::Item> Advances the iterator and returns the next value. [Read more](../iter/trait.iterator#tymethod.next) [source](https://doc.rust-lang.org/src/std/sys_common/process.rs.html#106-108)#### fn size\_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. [Read more](../iter/trait.iterator#method.size_hint) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#138-142)#### fn next\_chunk<const N: usize>( &mut self) -> Result<[Self::Item; N], IntoIter<Self::Item, N>> 🔬This is a nightly-only experimental API. (`iter_next_chunk` [#98326](https://github.com/rust-lang/rust/issues/98326)) Advances the iterator and returns an array containing the next `N` values. [Read more](../iter/trait.iterator#method.next_chunk) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#252-254)1.0.0 · #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. [Read more](../iter/trait.iterator#method.count) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#282-284)1.0.0 · #### fn last(self) -> Option<Self::Item> Consumes the iterator, returning the last element. [Read more](../iter/trait.iterator#method.last) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#328)#### fn advance\_by(&mut self, n: usize) -> Result<(), usize> 🔬This is a nightly-only experimental API. (`iter_advance_by` [#77404](https://github.com/rust-lang/rust/issues/77404)) Advances the iterator by `n` elements. [Read more](../iter/trait.iterator#method.advance_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#376)1.0.0 · #### fn nth(&mut self, n: usize) -> Option<Self::Item> Returns the `n`th element of the iterator. [Read more](../iter/trait.iterator#method.nth) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#428-430)1.28.0 · #### fn step\_by(self, step: usize) -> StepBy<Self> Notable traits for [StepBy](../iter/struct.stepby "struct std::iter::StepBy")<I> ``` impl<I> Iterator for StepBy<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator starting at the same point, but stepping by the given amount at each iteration. [Read more](../iter/trait.iterator#method.step_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#499-502)1.0.0 · #### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")<Item = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Notable traits for [Chain](../iter/struct.chain "struct std::iter::Chain")<A, B> ``` impl<A, B> Iterator for Chain<A, B>where     A: Iterator,     B: Iterator<Item = <A as Iterator>::Item>, type Item = <A as Iterator>::Item; ``` Takes two iterators and creates a new iterator over both in sequence. [Read more](../iter/trait.iterator#method.chain) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#617-620)1.0.0 · #### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Notable traits for [Zip](../iter/struct.zip "struct std::iter::Zip")<A, B> ``` impl<A, B> Iterator for Zip<A, B>where     A: Iterator,     B: Iterator, type Item = (<A as Iterator>::Item, <B as Iterator>::Item); ``` ‘Zips up’ two iterators into a single iterator of pairs. [Read more](../iter/trait.iterator#method.zip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#717-720)#### fn intersperse\_with<G>(self, separator: G) -> IntersperseWith<Self, G>where G: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")() -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Notable traits for [IntersperseWith](../iter/struct.interspersewith "struct std::iter::IntersperseWith")<I, G> ``` impl<I, G> Iterator for IntersperseWith<I, G>where     I: Iterator,     G: FnMut() -> <I as Iterator>::Item, type Item = <I as Iterator>::Item; ``` 🔬This is a nightly-only experimental API. (`iter_intersperse` [#79524](https://github.com/rust-lang/rust/issues/79524)) Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. [Read more](../iter/trait.iterator#method.intersperse_with) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#776-779)1.0.0 · #### fn map<B, F>(self, f: F) -> Map<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Notable traits for [Map](../iter/struct.map "struct std::iter::Map")<I, F> ``` impl<B, I, F> Iterator for Map<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> B, type Item = B; ``` Takes a closure and creates an iterator which calls that closure on each element. [Read more](../iter/trait.iterator#method.map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#821-824)1.21.0 · #### fn for\_each<F>(self, f: F)where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Calls a closure on each element of an iterator. [Read more](../iter/trait.iterator#method.for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#896-899)1.0.0 · #### fn filter<P>(self, predicate: P) -> Filter<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [Filter](../iter/struct.filter "struct std::iter::Filter")<I, P> ``` impl<I, P> Iterator for Filter<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator which uses a closure to determine if an element should be yielded. [Read more](../iter/trait.iterator#method.filter) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#941-944)1.0.0 · #### fn filter\_map<B, F>(self, f: F) -> FilterMap<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [FilterMap](../iter/struct.filtermap "struct std::iter::FilterMap")<I, F> ``` impl<B, I, F> Iterator for FilterMap<I, F>where     I: Iterator,     F: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both filters and maps. [Read more](../iter/trait.iterator#method.filter_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#987-989)1.0.0 · #### fn enumerate(self) -> Enumerate<Self> Notable traits for [Enumerate](../iter/struct.enumerate "struct std::iter::Enumerate")<I> ``` impl<I> Iterator for Enumerate<I>where     I: Iterator, type Item = (usize, <I as Iterator>::Item); ``` Creates an iterator which gives the current iteration count as well as the next value. [Read more](../iter/trait.iterator#method.enumerate) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1058-1060)1.0.0 · #### fn peekable(self) -> Peekable<Self> Notable traits for [Peekable](../iter/struct.peekable "struct std::iter::Peekable")<I> ``` impl<I> Iterator for Peekable<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which can use the [`peek`](../iter/struct.peekable#method.peek) and [`peek_mut`](../iter/struct.peekable#method.peek_mut) methods to look at the next element of the iterator without consuming it. See their documentation for more information. [Read more](../iter/trait.iterator#method.peekable) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1123-1126)1.0.0 · #### fn skip\_while<P>(self, predicate: P) -> SkipWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [SkipWhile](../iter/struct.skipwhile "struct std::iter::SkipWhile")<I, P> ``` impl<I, P> Iterator for SkipWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that [`skip`](../iter/trait.iterator#method.skip)s elements based on a predicate. [Read more](../iter/trait.iterator#method.skip_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1204-1207)1.0.0 · #### fn take\_while<P>(self, predicate: P) -> TakeWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Notable traits for [TakeWhile](../iter/struct.takewhile "struct std::iter::TakeWhile")<I, P> ``` impl<I, P> Iterator for TakeWhile<I, P>where     I: Iterator,     P: FnMut(&<I as Iterator>::Item) -> bool, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields elements based on a predicate. [Read more](../iter/trait.iterator#method.take_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1292-1295)#### fn map\_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [MapWhile](../iter/struct.mapwhile "struct std::iter::MapWhile")<I, P> ``` impl<B, I, P> Iterator for MapWhile<I, P>where     I: Iterator,     P: FnMut(<I as Iterator>::Item) -> Option<B>, type Item = B; ``` Creates an iterator that both yields elements based on a predicate and maps. [Read more](../iter/trait.iterator#method.map_while) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1323-1325)1.0.0 · #### fn skip(self, n: usize) -> Skip<Self> Notable traits for [Skip](../iter/struct.skip "struct std::iter::Skip")<I> ``` impl<I> Iterator for Skip<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that skips the first `n` elements. [Read more](../iter/trait.iterator#method.skip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1376-1378)1.0.0 · #### fn take(self, n: usize) -> Take<Self> Notable traits for [Take](../iter/struct.take "struct std::iter::Take")<I> ``` impl<I> Iterator for Take<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. [Read more](../iter/trait.iterator#method.take) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1420-1423)1.0.0 · #### fn scan<St, B, F>(self, initial\_state: St, f: F) -> Scan<Self, St, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")([&mut](../primitive.reference) St, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Notable traits for [Scan](../iter/struct.scan "struct std::iter::Scan")<I, St, F> ``` impl<B, I, St, F> Iterator for Scan<I, St, F>where     I: Iterator,     F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>, type Item = B; ``` An iterator adapter similar to [`fold`](../iter/trait.iterator#method.fold) that holds internal state and produces a new iterator. [Read more](../iter/trait.iterator#method.scan) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1464)1.0.0 · #### fn flat\_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where U: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> U, Notable traits for [FlatMap](../iter/struct.flatmap "struct std::iter::FlatMap")<I, U, F> ``` impl<I, U, F> Iterator for FlatMap<I, U, F>where     I: Iterator,     U: IntoIterator,     F: FnMut(<I as Iterator>::Item) -> U, type Item = <U as IntoIterator>::Item; ``` Creates an iterator that works like map, but flattens nested structure. [Read more](../iter/trait.iterator#method.flat_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1600-1602)1.0.0 · #### fn fuse(self) -> Fuse<Self> Notable traits for [Fuse](../iter/struct.fuse "struct std::iter::Fuse")<I> ``` impl<I> Iterator for Fuse<I>where     I: Iterator, type Item = <I as Iterator>::Item; ``` Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "None"). [Read more](../iter/trait.iterator#method.fuse) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1684-1687)1.0.0 · #### fn inspect<F>(self, f: F) -> Inspect<Self, F>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")), Notable traits for [Inspect](../iter/struct.inspect "struct std::iter::Inspect")<I, F> ``` impl<I, F> Iterator for Inspect<I, F>where     I: Iterator,     F: FnMut(&<I as Iterator>::Item), type Item = <I as Iterator>::Item; ``` Does something with each element of an iterator, passing the value on. [Read more](../iter/trait.iterator#method.inspect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1714-1716)1.0.0 · #### fn by\_ref(&mut self) -> &mut Self Borrows an iterator, rather than consuming it. [Read more](../iter/trait.iterator#method.by_ref) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1832-1834)1.0.0 · #### fn collect<B>(self) -> Bwhere B: [FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Transforms an iterator into a collection. [Read more](../iter/trait.iterator#method.collect) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1983-1985)#### fn collect\_into<E>(self, collection: &mut E) -> &mut Ewhere E: [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, 🔬This is a nightly-only experimental API. (`iter_collect_into` [#94780](https://github.com/rust-lang/rust/issues/94780)) Collects all the items from an iterator into a collection. [Read more](../iter/trait.iterator#method.collect_into) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2017-2021)1.0.0 · #### fn partition<B, F>(self, f: F) -> (B, B)where B: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Consumes an iterator, creating two collections from it. [Read more](../iter/trait.iterator#method.partition) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2136-2139)#### fn is\_partitioned<P>(self, predicate: P) -> boolwhere P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_is_partitioned` [#62544](https://github.com/rust-lang/rust/issues/62544)) Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. [Read more](../iter/trait.iterator#method.is_partitioned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2230-2234)1.27.0 · #### fn try\_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. [Read more](../iter/trait.iterator#method.try_fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2288-2292)1.27.0 · #### fn try\_for\_each<F, R>(&mut self, f: F) -> Rwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [()](../primitive.unit)>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. [Read more](../iter/trait.iterator#method.try_for_each) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2407-2410)1.0.0 · #### fn fold<B, F>(self, init: B, f: F) -> Bwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(B, Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Folds every element into an accumulator by applying an operation, returning the final result. [Read more](../iter/trait.iterator#method.fold) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2453-2456)1.51.0 · #### fn reduce<F>(self, f: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Reduces the elements to a single one, by repeatedly applying a reducing operation. [Read more](../iter/trait.iterator#method.reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2524-2529)#### fn try\_reduce<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce` [#87053](https://github.com/rust-lang/rust/issues/87053)) Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. [Read more](../iter/trait.iterator#method.try_reduce) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2581-2584)1.0.0 · #### fn all<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if every element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.all) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2634-2637)1.0.0 · #### fn any<F>(&mut self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Tests if any element of the iterator matches a predicate. [Read more](../iter/trait.iterator#method.any) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2694-2697)1.0.0 · #### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element of an iterator that satisfies a predicate. [Read more](../iter/trait.iterator#method.find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2725-2728)1.30.0 · #### fn find\_map<B, F>(&mut self, f: F) -> Option<B>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<B>, Applies function to the elements of iterator and returns the first non-none result. [Read more](../iter/trait.iterator#method.find_map) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2781-2786)#### fn try\_find<F, R>( &mut self, f: F) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> R, R: [Try](../ops/trait.try "trait std::ops::Try")<Output = [bool](../primitive.bool)>, <R as [Try](../ops/trait.try "trait std::ops::Try")>::[Residual](../ops/trait.try#associatedtype.Residual "type std::ops::Try::Residual"): [Residual](../ops/trait.residual "trait std::ops::Residual")<[Option](../option/enum.option "enum std::option::Option")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>>, 🔬This is a nightly-only experimental API. (`try_find` [#63178](https://github.com/rust-lang/rust/issues/63178)) Applies function to the elements of iterator and returns the first true result or the first error. [Read more](../iter/trait.iterator#method.try_find) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2863-2866)1.0.0 · #### fn position<P>(&mut self, predicate: P) -> Option<usize>where P: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [bool](../primitive.bool), Searches for an element in an iterator, returning its index. [Read more](../iter/trait.iterator#method.position) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3031-3034)1.6.0 · #### fn max\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the maximum value from the specified function. [Read more](../iter/trait.iterator#method.max_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3064-3067)1.15.0 · #### fn max\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the maximum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.max_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3091-3094)1.6.0 · #### fn min\_by\_key<B, F>(self, f: F) -> Option<Self::Item>where B: [Ord](../cmp/trait.ord "trait std::cmp::Ord"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> B, Returns the element that gives the minimum value from the specified function. [Read more](../iter/trait.iterator#method.min_by_key) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3124-3127)1.15.0 · #### fn min\_by<F>(self, compare: F) -> Option<Self::Item>where F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), Returns the element that gives the minimum value with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.min_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3199-3203)1.0.0 · #### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<A>, FromB: [Default](../default/trait.default "trait std::default::Default") + [Extend](../iter/trait.extend "trait std::iter::Extend")<B>, Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [(A, B)](../primitive.tuple)>, Converts an iterator of pairs into a pair of containers. [Read more](../iter/trait.iterator#method.unzip) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3231-3234)1.36.0 · #### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + [Copy](../marker/trait.copy "trait std::marker::Copy"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Copied](../iter/struct.copied "struct std::iter::Copied")<I> ``` impl<'a, I, T> Iterator for Copied<I>where     T: 'a + Copy,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which copies all of its elements. [Read more](../iter/trait.iterator#method.copied) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3278-3281)1.0.0 · #### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + [Clone](../clone/trait.clone "trait std::clone::Clone"), Self: [Iterator](../iter/trait.iterator "trait std::iter::Iterator")<Item = [&'a](../primitive.reference) T>, Notable traits for [Cloned](../iter/struct.cloned "struct std::iter::Cloned")<I> ``` impl<'a, I, T> Iterator for Cloned<I>where     T: 'a + Clone,     I: Iterator<Item = &'a T>, type Item = T; ``` Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone)s all of its elements. [Read more](../iter/trait.iterator#method.cloned) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3355-3357)#### fn array\_chunks<const N: usize>(self) -> ArrayChunks<Self, N> Notable traits for [ArrayChunks](../iter/struct.arraychunks "struct std::iter::ArrayChunks")<I, N> ``` impl<I, const N: usize> Iterator for ArrayChunks<I, N>where     I: Iterator, type Item = [<I as Iterator>::Item; N]; ``` 🔬This is a nightly-only experimental API. (`iter_array_chunks` [#100450](https://github.com/rust-lang/rust/issues/100450)) Returns an iterator over `N` elements of the iterator at a time. [Read more](../iter/trait.iterator#method.array_chunks) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3385-3388)1.11.0 · #### fn sum<S>(self) -> Swhere S: [Sum](../iter/trait.sum "trait std::iter::Sum")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Sums the elements of an iterator. [Read more](../iter/trait.iterator#method.sum) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3414-3417)1.11.0 · #### fn product<P>(self) -> Pwhere P: [Product](../iter/trait.product "trait std::iter::Product")<Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")>, Iterates over the entire iterator, multiplying all the elements [Read more](../iter/trait.iterator#method.product) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3464-3468)#### fn cmp\_by<I, F>(self, other: I, cmp: F) -> Orderingwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Ordering](../cmp/enum.ordering "enum std::cmp::Ordering"), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3511-3515)1.5.0 · #### fn partial\_cmp<I>(self, other: I) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another. [Read more](../iter/trait.iterator#method.partial_cmp) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3549-3553)#### fn partial\_cmp\_by<I, F>(self, other: I, partial\_cmp: F) -> Option<Ordering>where I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) [Lexicographically](../cmp/trait.ord#lexicographical-comparison) compares the elements of this [`Iterator`](../iter/trait.iterator "Iterator") with those of another with respect to the specified comparison function. [Read more](../iter/trait.iterator#method.partial_cmp_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3591-3595)1.5.0 · #### fn eq<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another. [Read more](../iter/trait.iterator#method.eq) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3616-3620)#### fn eq\_by<I, F>(self, other: I, eq: F) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), <I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")) -> [bool](../primitive.bool), 🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295)) Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are equal to those of another with respect to the specified equality function. [Read more](../iter/trait.iterator#method.eq_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3651-3655)1.5.0 · #### fn ne<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are unequal to those of another. [Read more](../iter/trait.iterator#method.ne) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3672-3676)1.5.0 · #### fn lt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less than those of another. [Read more](../iter/trait.iterator#method.lt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3693-3697)1.5.0 · #### fn le<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) less or equal to those of another. [Read more](../iter/trait.iterator#method.le) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3714-3718)1.5.0 · #### fn gt<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than those of another. [Read more](../iter/trait.iterator#method.gt) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3735-3739)1.5.0 · #### fn ge<I>(self, other: I) -> boolwhere I: [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"): [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<<I as [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator")>::[Item](../iter/trait.intoiterator#associatedtype.Item "type std::iter::IntoIterator::Item")>, Determines if the elements of this [`Iterator`](../iter/trait.iterator "Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison) greater than or equal to those of another. [Read more](../iter/trait.iterator#method.ge) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3794-3797)#### fn is\_sorted\_by<F>(self, compare: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(&Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item"), &Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> [Option](../option/enum.option "enum std::option::Option")<[Ordering](../cmp/enum.ordering "enum std::cmp::Ordering")>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given comparator function. [Read more](../iter/trait.iterator#method.is_sorted_by) [source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3840-3844)#### fn is\_sorted\_by\_key<F, K>(self, f: F) -> boolwhere F: [FnMut](../ops/trait.fnmut "trait std::ops::FnMut")(Self::[Item](../iter/trait.iterator#associatedtype.Item "type std::iter::Iterator::Item")) -> K, K: [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd")<K>, 🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485)) Checks if the elements of this iterator are sorted using the given key extraction function. [Read more](../iter/trait.iterator#method.is_sorted_by_key) Auto Trait Implementations -------------------------- ### impl<'a> RefUnwindSafe for CommandEnvs<'a> ### impl<'a> Send for CommandEnvs<'a> ### impl<'a> Sync for CommandEnvs<'a> ### impl<'a> Unpin for CommandEnvs<'a> ### impl<'a> UnwindSafe for CommandEnvs<'a> Blanket Implementations ----------------------- [source](https://doc.rust-lang.org/src/core/any.rs.html#200)### impl<T> Any for Twhere T: 'static + ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/any.rs.html#201)#### fn type\_id(&self) -> TypeId Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#209)### impl<T> Borrow<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#211)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow(&self) -> &T Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow) [source](https://doc.rust-lang.org/src/core/borrow.rs.html#218)### impl<T> BorrowMut<T> for Twhere T: ?[Sized](../marker/trait.sized "trait std::marker::Sized"), [source](https://doc.rust-lang.org/src/core/borrow.rs.html#219)const: [unstable](https://github.com/rust-lang/rust/issues/91522 "Tracking issue for const_borrow") · #### fn borrow\_mut(&mut self) -> &mut T Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#559)### impl<T> From<T> for T [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#562)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn from(t: T) -> T Returns the argument unchanged. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#543)### impl<T, U> Into<U> for Twhere U: [From](../convert/trait.from "trait std::convert::From")<T>, [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#551)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `[From](../convert/trait.from "From")<T> for U` chooses to do. [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#266)### impl<I> IntoIterator for Iwhere I: [Iterator](../iter/trait.iterator "trait std::iter::Iterator"), #### type Item = <I as Iterator>::Item The type of the elements being iterated over. #### type IntoIter = I Which kind of iterator are we turning this into? [source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#271)const: [unstable](https://github.com/rust-lang/rust/issues/90603 "Tracking issue for const_intoiterator_identity") · #### fn into\_iter(self) -> I Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter) [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#601)### impl<T, U> TryFrom<U> for Twhere U: [Into](../convert/trait.into "trait std::convert::Into")<T>, #### type Error = Infallible The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#607)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> Performs the conversion. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#586)### impl<T, U> TryInto<U> for Twhere U: [TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom")<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. [source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#592)const: [unstable](https://github.com/rust-lang/rust/issues/88674 "Tracking issue for const_convert") · #### fn try\_into(self) -> Result<U, <U as TryFrom<T>>::Error> Performs the conversion.
programming_docs
rust Function std::process::exit Function std::process::exit =========================== ``` pub fn exit(code: i32) -> ! ``` Terminates the current process with the specified exit code. This function will never return and will immediately terminate the current process. The exit code is passed through to the underlying OS and will be available for consumption by another process. Note that because this function never returns, and that it terminates the process, no destructors on the current stack or any other thread’s stack will be run. If a clean shutdown is needed it is recommended to only call this function at a known point where there are no more destructors left to run; or, preferably, simply return a type implementing [`Termination`](trait.termination "Termination") (such as [`ExitCode`](struct.exitcode "ExitCode") or `Result`) from the `main` function and avoid this function altogether: ``` fn main() -> Result<(), MyError> { // ... Ok(()) } ``` ### Platform-specific behavior **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit` will be visible to a parent process inspecting the exit code. On most Unix-like platforms, only the eight least-significant bits are considered. For example, the exit code for this example will be `0` on Linux, but `256` on Windows: ``` use std::process; process::exit(0x0100); ``` rust Constant std::f64::NAN Constant std::f64::NAN ====================== ``` pub const NAN: f64 = f64::NAN; // NaNf64 ``` 👎Deprecating in a future Rust version: replaced by the `NAN` associated constant on `f64` Not a Number (NaN). Use [`f64::NAN`](../primitive.f64#associatedconstant.NAN "f64::NAN") instead. Examples -------- ``` // deprecated way let nan = std::f64::NAN; // intended way let nan = f64::NAN; ``` rust Constant std::f64::MIN_10_EXP Constant std::f64::MIN\_10\_EXP =============================== ``` pub const MIN_10_EXP: i32 = f64::MIN_10_EXP; // -307i32 ``` 👎Deprecating in a future Rust version: replaced by the `MIN_10_EXP` associated constant on `f64` Minimum possible normal power of 10 exponent. Use [`f64::MIN_10_EXP`](../primitive.f64#associatedconstant.MIN_10_EXP "f64::MIN_10_EXP") instead. Examples -------- ``` // deprecated way let min = std::f64::MIN_10_EXP; // intended way let min = f64::MIN_10_EXP; ``` rust Module std::f64 Module std::f64 =============== Constants for the `f64` double-precision floating point type. *[See also the `f64` primitive type](../primitive.f64).* Mathematically significant numbers are provided in the `consts` sub-module. For the constants defined directly in this module (as distinct from those defined in the `consts` sub-module), new code should instead use the associated constants defined directly on the `f64` type. Modules ------- [consts](consts/index "std::f64::consts mod") Basic mathematical constants. Constants --------- [DIGITS](constant.digits "std::f64::DIGITS constant")Deprecation planned Approximate number of significant digits in base 10. Use [`f64::DIGITS`](../primitive.f64#associatedconstant.DIGITS "f64::DIGITS") instead. [EPSILON](constant.epsilon "std::f64::EPSILON constant")Deprecation planned [Machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon) value for `f64`. Use [`f64::EPSILON`](../primitive.f64#associatedconstant.EPSILON "f64::EPSILON") instead. [INFINITY](constant.infinity "std::f64::INFINITY constant")Deprecation planned Infinity (∞). Use [`f64::INFINITY`](../primitive.f64#associatedconstant.INFINITY "f64::INFINITY") instead. [MANTISSA\_DIGITS](constant.mantissa_digits "std::f64::MANTISSA_DIGITS constant")Deprecation planned Number of significant digits in base 2. Use [`f64::MANTISSA_DIGITS`](../primitive.f64#associatedconstant.MANTISSA_DIGITS "f64::MANTISSA_DIGITS") instead. [MAX](constant.max "std::f64::MAX constant")Deprecation planned Largest finite `f64` value. Use [`f64::MAX`](../primitive.f64#associatedconstant.MAX "f64::MAX") instead. [MAX\_10\_EXP](constant.max_10_exp "std::f64::MAX_10_EXP constant")Deprecation planned Maximum possible power of 10 exponent. Use [`f64::MAX_10_EXP`](../primitive.f64#associatedconstant.MAX_10_EXP "f64::MAX_10_EXP") instead. [MAX\_EXP](constant.max_exp "std::f64::MAX_EXP constant")Deprecation planned Maximum possible power of 2 exponent. Use [`f64::MAX_EXP`](../primitive.f64#associatedconstant.MAX_EXP "f64::MAX_EXP") instead. [MIN](constant.min "std::f64::MIN constant")Deprecation planned Smallest finite `f64` value. Use [`f64::MIN`](../primitive.f64#associatedconstant.MIN "f64::MIN") instead. [MIN\_10\_EXP](constant.min_10_exp "std::f64::MIN_10_EXP constant")Deprecation planned Minimum possible normal power of 10 exponent. Use [`f64::MIN_10_EXP`](../primitive.f64#associatedconstant.MIN_10_EXP "f64::MIN_10_EXP") instead. [MIN\_EXP](constant.min_exp "std::f64::MIN_EXP constant")Deprecation planned One greater than the minimum possible normal power of 2 exponent. Use [`f64::MIN_EXP`](../primitive.f64#associatedconstant.MIN_EXP "f64::MIN_EXP") instead. [MIN\_POSITIVE](constant.min_positive "std::f64::MIN_POSITIVE constant")Deprecation planned Smallest positive normal `f64` value. Use [`f64::MIN_POSITIVE`](../primitive.f64#associatedconstant.MIN_POSITIVE "f64::MIN_POSITIVE") instead. [NAN](constant.nan "std::f64::NAN constant")Deprecation planned Not a Number (NaN). Use [`f64::NAN`](../primitive.f64#associatedconstant.NAN "f64::NAN") instead. [NEG\_INFINITY](constant.neg_infinity "std::f64::NEG_INFINITY constant")Deprecation planned Negative infinity (−∞). Use [`f64::NEG_INFINITY`](../primitive.f64#associatedconstant.NEG_INFINITY "f64::NEG_INFINITY") instead. [RADIX](constant.radix "std::f64::RADIX constant")Deprecation planned The radix or base of the internal representation of `f64`. Use [`f64::RADIX`](../primitive.f64#associatedconstant.RADIX "f64::RADIX") instead. rust Constant std::f64::MAX Constant std::f64::MAX ====================== ``` pub const MAX: f64 = f64::MAX; // 1.7976931348623157E+308f64 ``` 👎Deprecating in a future Rust version: replaced by the `MAX` associated constant on `f64` Largest finite `f64` value. Use [`f64::MAX`](../primitive.f64#associatedconstant.MAX "f64::MAX") instead. Examples -------- ``` // deprecated way let max = std::f64::MAX; // intended way let max = f64::MAX; ``` rust Constant std::f64::MIN Constant std::f64::MIN ====================== ``` pub const MIN: f64 = f64::MIN; // -1.7976931348623157E+308f64 ``` 👎Deprecating in a future Rust version: replaced by the `MIN` associated constant on `f64` Smallest finite `f64` value. Use [`f64::MIN`](../primitive.f64#associatedconstant.MIN "f64::MIN") instead. Examples -------- ``` // deprecated way let min = std::f64::MIN; // intended way let min = f64::MIN; ``` rust Constant std::f64::EPSILON Constant std::f64::EPSILON ========================== ``` pub const EPSILON: f64 = f64::EPSILON; // 2.2204460492503131E-16f64 ``` 👎Deprecating in a future Rust version: replaced by the `EPSILON` associated constant on `f64` [Machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon) value for `f64`. Use [`f64::EPSILON`](../primitive.f64#associatedconstant.EPSILON "f64::EPSILON") instead. This is the difference between `1.0` and the next larger representable number. Examples -------- ``` // deprecated way let e = std::f64::EPSILON; // intended way let e = f64::EPSILON; ``` rust Constant std::f64::MAX_10_EXP Constant std::f64::MAX\_10\_EXP =============================== ``` pub const MAX_10_EXP: i32 = f64::MAX_10_EXP; // 308i32 ``` 👎Deprecating in a future Rust version: replaced by the `MAX_10_EXP` associated constant on `f64` Maximum possible power of 10 exponent. Use [`f64::MAX_10_EXP`](../primitive.f64#associatedconstant.MAX_10_EXP "f64::MAX_10_EXP") instead. Examples -------- ``` // deprecated way let max = std::f64::MAX_10_EXP; // intended way let max = f64::MAX_10_EXP; ``` rust Constant std::f64::MIN_EXP Constant std::f64::MIN\_EXP =========================== ``` pub const MIN_EXP: i32 = f64::MIN_EXP; // -1_021i32 ``` 👎Deprecating in a future Rust version: replaced by the `MIN_EXP` associated constant on `f64` One greater than the minimum possible normal power of 2 exponent. Use [`f64::MIN_EXP`](../primitive.f64#associatedconstant.MIN_EXP "f64::MIN_EXP") instead. Examples -------- ``` // deprecated way let min = std::f64::MIN_EXP; // intended way let min = f64::MIN_EXP; ``` rust Constant std::f64::RADIX Constant std::f64::RADIX ======================== ``` pub const RADIX: u32 = f64::RADIX; // 2u32 ``` 👎Deprecating in a future Rust version: replaced by the `RADIX` associated constant on `f64` The radix or base of the internal representation of `f64`. Use [`f64::RADIX`](../primitive.f64#associatedconstant.RADIX "f64::RADIX") instead. Examples -------- ``` // deprecated way let r = std::f64::RADIX; // intended way let r = f64::RADIX; ``` rust Constant std::f64::MIN_POSITIVE Constant std::f64::MIN\_POSITIVE ================================ ``` pub const MIN_POSITIVE: f64 = f64::MIN_POSITIVE; // 2.2250738585072014E-308f64 ``` 👎Deprecating in a future Rust version: replaced by the `MIN_POSITIVE` associated constant on `f64` Smallest positive normal `f64` value. Use [`f64::MIN_POSITIVE`](../primitive.f64#associatedconstant.MIN_POSITIVE "f64::MIN_POSITIVE") instead. Examples -------- ``` // deprecated way let min = std::f64::MIN_POSITIVE; // intended way let min = f64::MIN_POSITIVE; ``` rust Constant std::f64::MAX_EXP Constant std::f64::MAX\_EXP =========================== ``` pub const MAX_EXP: i32 = f64::MAX_EXP; // 1_024i32 ``` 👎Deprecating in a future Rust version: replaced by the `MAX_EXP` associated constant on `f64` Maximum possible power of 2 exponent. Use [`f64::MAX_EXP`](../primitive.f64#associatedconstant.MAX_EXP "f64::MAX_EXP") instead. Examples -------- ``` // deprecated way let max = std::f64::MAX_EXP; // intended way let max = f64::MAX_EXP; ``` rust Constant std::f64::MANTISSA_DIGITS Constant std::f64::MANTISSA\_DIGITS =================================== ``` pub const MANTISSA_DIGITS: u32 = f64::MANTISSA_DIGITS; // 53u32 ``` 👎Deprecating in a future Rust version: replaced by the `MANTISSA_DIGITS` associated constant on `f64` Number of significant digits in base 2. Use [`f64::MANTISSA_DIGITS`](../primitive.f64#associatedconstant.MANTISSA_DIGITS "f64::MANTISSA_DIGITS") instead. Examples -------- ``` // deprecated way let d = std::f64::MANTISSA_DIGITS; // intended way let d = f64::MANTISSA_DIGITS; ``` rust Constant std::f64::INFINITY Constant std::f64::INFINITY =========================== ``` pub const INFINITY: f64 = f64::INFINITY; // +Inff64 ``` 👎Deprecating in a future Rust version: replaced by the `INFINITY` associated constant on `f64` Infinity (∞). Use [`f64::INFINITY`](../primitive.f64#associatedconstant.INFINITY "f64::INFINITY") instead. Examples -------- ``` // deprecated way let inf = std::f64::INFINITY; // intended way let inf = f64::INFINITY; ``` rust Constant std::f64::DIGITS Constant std::f64::DIGITS ========================= ``` pub const DIGITS: u32 = f64::DIGITS; // 15u32 ``` 👎Deprecating in a future Rust version: replaced by the `DIGITS` associated constant on `f64` Approximate number of significant digits in base 10. Use [`f64::DIGITS`](../primitive.f64#associatedconstant.DIGITS "f64::DIGITS") instead. Examples -------- ``` // deprecated way let d = std::f64::DIGITS; // intended way let d = f64::DIGITS; ``` rust Constant std::f64::NEG_INFINITY Constant std::f64::NEG\_INFINITY ================================ ``` pub const NEG_INFINITY: f64 = f64::NEG_INFINITY; // -Inff64 ``` 👎Deprecating in a future Rust version: replaced by the `NEG_INFINITY` associated constant on `f64` Negative infinity (−∞). Use [`f64::NEG_INFINITY`](../primitive.f64#associatedconstant.NEG_INFINITY "f64::NEG_INFINITY") instead. Examples -------- ``` // deprecated way let ninf = std::f64::NEG_INFINITY; // intended way let ninf = f64::NEG_INFINITY; ``` rust Constant std::f64::consts::FRAC_PI_6 Constant std::f64::consts::FRAC\_PI\_6 ====================================== ``` pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381f64; // 0.52359877559829893f64 ``` π/6 rust Constant std::f64::consts::E Constant std::f64::consts::E ============================ ``` pub const E: f64 = 2.71828182845904523536028747135266250f64; // 2.7182818284590451f64 ``` Euler’s number (e) rust Module std::f64::consts Module std::f64::consts ======================= Basic mathematical constants. Constants --------- [E](constant.e "std::f64::consts::E constant") Euler’s number (e) [FRAC\_1\_PI](constant.frac_1_pi "std::f64::consts::FRAC_1_PI constant") 1/π [FRAC\_1\_SQRT\_2](constant.frac_1_sqrt_2 "std::f64::consts::FRAC_1_SQRT_2 constant") 1/sqrt(2) [FRAC\_2\_PI](constant.frac_2_pi "std::f64::consts::FRAC_2_PI constant") 2/π [FRAC\_2\_SQRT\_PI](constant.frac_2_sqrt_pi "std::f64::consts::FRAC_2_SQRT_PI constant") 2/sqrt(π) [FRAC\_PI\_2](constant.frac_pi_2 "std::f64::consts::FRAC_PI_2 constant") π/2 [FRAC\_PI\_3](constant.frac_pi_3 "std::f64::consts::FRAC_PI_3 constant") π/3 [FRAC\_PI\_4](constant.frac_pi_4 "std::f64::consts::FRAC_PI_4 constant") π/4 [FRAC\_PI\_6](constant.frac_pi_6 "std::f64::consts::FRAC_PI_6 constant") π/6 [FRAC\_PI\_8](constant.frac_pi_8 "std::f64::consts::FRAC_PI_8 constant") π/8 [LN\_2](constant.ln_2 "std::f64::consts::LN_2 constant") ln(2) [LN\_10](constant.ln_10 "std::f64::consts::LN_10 constant") ln(10) [LOG2\_10](constant.log2_10 "std::f64::consts::LOG2_10 constant") log2(10) [LOG2\_E](constant.log2_e "std::f64::consts::LOG2_E constant") log2(e) [LOG10\_2](constant.log10_2 "std::f64::consts::LOG10_2 constant") log10(2) [LOG10\_E](constant.log10_e "std::f64::consts::LOG10_E constant") log10(e) [PI](constant.pi "std::f64::consts::PI constant") Archimedes’ constant (π) [SQRT\_2](constant.sqrt_2 "std::f64::consts::SQRT_2 constant") sqrt(2) [TAU](constant.tau "std::f64::consts::TAU constant") The full circle constant (τ) rust Constant std::f64::consts::LOG2_10 Constant std::f64::consts::LOG2\_10 =================================== ``` pub const LOG2_10: f64 = 3.32192809488736234787031942948939018f64; // 3.3219280948873622f64 ``` log2(10) rust Constant std::f64::consts::PI Constant std::f64::consts::PI ============================= ``` pub const PI: f64 = 3.14159265358979323846264338327950288f64; // 3.1415926535897931f64 ``` Archimedes’ constant (π) rust Constant std::f64::consts::FRAC_PI_2 Constant std::f64::consts::FRAC\_PI\_2 ====================================== ``` pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144f64; // 1.5707963267948966f64 ``` π/2 rust Constant std::f64::consts::LOG10_2 Constant std::f64::consts::LOG10\_2 =================================== ``` pub const LOG10_2: f64 = 0.301029995663981195213738894724493027f64; // 0.3010299956639812f64 ``` log10(2) rust Constant std::f64::consts::FRAC_PI_3 Constant std::f64::consts::FRAC\_PI\_3 ====================================== ``` pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763f64; // 1.0471975511965979f64 ``` π/3 rust Constant std::f64::consts::SQRT_2 Constant std::f64::consts::SQRT\_2 ================================== ``` pub const SQRT_2: f64 = 1.41421356237309504880168872420969808f64; // 1.4142135623730951f64 ``` sqrt(2) rust Constant std::f64::consts::LOG10_E Constant std::f64::consts::LOG10\_E =================================== ``` pub const LOG10_E: f64 = 0.434294481903251827651128918916605082f64; // 0.43429448190325182f64 ``` log10(e) rust Constant std::f64::consts::FRAC_1_PI Constant std::f64::consts::FRAC\_1\_PI ====================================== ``` pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724f64; // 0.31830988618379069f64 ``` 1/π rust Constant std::f64::consts::FRAC_2_SQRT_PI Constant std::f64::consts::FRAC\_2\_SQRT\_PI ============================================ ``` pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517f64; // 1.1283791670955126f64 ``` 2/sqrt(π) rust Constant std::f64::consts::FRAC_PI_4 Constant std::f64::consts::FRAC\_PI\_4 ====================================== ``` pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721f64; // 0.78539816339744828f64 ``` π/4 rust Constant std::f64::consts::LN_10 Constant std::f64::consts::LN\_10 ================================= ``` pub const LN_10: f64 = 2.30258509299404568401799145468436421f64; // 2.3025850929940459f64 ``` ln(10) rust Constant std::f64::consts::FRAC_1_SQRT_2 Constant std::f64::consts::FRAC\_1\_SQRT\_2 =========================================== ``` pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039f64; // 0.70710678118654757f64 ``` 1/sqrt(2) rust Constant std::f64::consts::FRAC_PI_8 Constant std::f64::consts::FRAC\_PI\_8 ====================================== ``` pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786f64; // 0.39269908169872414f64 ``` π/8 rust Constant std::f64::consts::TAU Constant std::f64::consts::TAU ============================== ``` pub const TAU: f64 = 6.28318530717958647692528676655900577f64; // 6.2831853071795862f64 ``` The full circle constant (τ) Equal to 2π. rust Constant std::f64::consts::FRAC_2_PI Constant std::f64::consts::FRAC\_2\_PI ====================================== ``` pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448f64; // 0.63661977236758138f64 ``` 2/π rust Constant std::f64::consts::LN_2 Constant std::f64::consts::LN\_2 ================================ ``` pub const LN_2: f64 = 0.693147180559945309417232121458176568f64; // 0.69314718055994529f64 ``` ln(2) rust Constant std::f64::consts::LOG2_E Constant std::f64::consts::LOG2\_E ================================== ``` pub const LOG2_E: f64 = 1.44269504088896340735992468100189214f64; // 1.4426950408889634f64 ``` log2(e) rust Bringing Paths into Scope with the use Keyword Bringing Paths into Scope with the `use` Keyword ================================================ Having to write out the paths to call functions can feel inconvenient and repetitive. In Listing 7-7, whether we chose the absolute or relative path to the `add_to_waitlist` function, every time we wanted to call `add_to_waitlist` we had to specify `front_of_house` and `hosting` too. Fortunately, there’s a way to simplify this process: we can create a shortcut to a path with the `use` keyword once, and then use the shorter name everywhere else in the scope. In Listing 7-11, we bring the `crate::front_of_house::hosting` module into the scope of the `eat_at_restaurant` function so we only have to specify `hosting::add_to_waitlist` to call the `add_to_waitlist` function in `eat_at_restaurant`. Filename: src/lib.rs ``` mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} } } use crate::front_of_house::hosting; pub fn eat_at_restaurant() { hosting::add_to_waitlist(); } ``` Listing 7-11: Bringing a module into scope with `use` Adding `use` and a path in a scope is similar to creating a symbolic link in the filesystem. By adding `use crate::front_of_house::hosting` in the crate root, `hosting` is now a valid name in that scope, just as though the `hosting` module had been defined in the crate root. Paths brought into scope with `use` also check privacy, like any other paths. Note that `use` only creates the shortcut for the particular scope in which the `use` occurs. Listing 7-12 moves the `eat_at_restaurant` function into a new child module named `customer`, which is then a different scope than the `use` statement, so the function body won’t compile: Filename: src/lib.rs ``` mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} } } use crate::front_of_house::hosting; mod customer { pub fn eat_at_restaurant() { hosting::add_to_waitlist(); } } ``` Listing 7-12: A `use` statement only applies in the scope it’s in The compiler error shows that the shortcut no longer applies within the `customer` module: ``` $ cargo build Compiling restaurant v0.1.0 (file:///projects/restaurant) error[E0433]: failed to resolve: use of undeclared crate or module `hosting` --> src/lib.rs:11:9 | 11 | hosting::add_to_waitlist(); | ^^^^^^^ use of undeclared crate or module `hosting` warning: unused import: `crate::front_of_house::hosting` --> src/lib.rs:7:5 | 7 | use crate::front_of_house::hosting; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(unused_imports)]` on by default For more information about this error, try `rustc --explain E0433`. warning: `restaurant` (lib) generated 1 warning error: could not compile `restaurant` due to previous error; 1 warning emitted ``` Notice there’s also a warning that the `use` is no longer used in its scope! To fix this problem, move the `use` within the `customer` module too, or reference the shortcut in the parent module with `super::hosting` within the child `customer` module. ### Creating Idiomatic `use` Paths In Listing 7-11, you might have wondered why we specified `use crate::front_of_house::hosting` and then called `hosting::add_to_waitlist` in `eat_at_restaurant` rather than specifying the `use` path all the way out to the `add_to_waitlist` function to achieve the same result, as in Listing 7-13. Filename: src/lib.rs ``` mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} } } use crate::front_of_house::hosting::add_to_waitlist; pub fn eat_at_restaurant() { add_to_waitlist(); } ``` Listing 7-13: Bringing the `add_to_waitlist` function into scope with `use`, which is unidiomatic Although both Listing 7-11 and 7-13 accomplish the same task, Listing 7-11 is the idiomatic way to bring a function into scope with `use`. Bringing the function’s parent module into scope with `use` means we have to specify the parent module when calling the function. Specifying the parent module when calling the function makes it clear that the function isn’t locally defined while still minimizing repetition of the full path. The code in Listing 7-13 is unclear as to where `add_to_waitlist` is defined. On the other hand, when bringing in structs, enums, and other items with `use`, it’s idiomatic to specify the full path. Listing 7-14 shows the idiomatic way to bring the standard library’s `HashMap` struct into the scope of a binary crate. Filename: src/main.rs ``` use std::collections::HashMap; fn main() { let mut map = HashMap::new(); map.insert(1, 2); } ``` Listing 7-14: Bringing `HashMap` into scope in an idiomatic way There’s no strong reason behind this idiom: it’s just the convention that has emerged, and folks have gotten used to reading and writing Rust code this way. The exception to this idiom is if we’re bringing two items with the same name into scope with `use` statements, because Rust doesn’t allow that. Listing 7-15 shows how to bring two `Result` types into scope that have the same name but different parent modules and how to refer to them. Filename: src/lib.rs ``` use std::fmt; use std::io; fn function1() -> fmt::Result { // --snip-- Ok(()) } fn function2() -> io::Result<()> { // --snip-- Ok(()) } ``` Listing 7-15: Bringing two types with the same name into the same scope requires using their parent modules. As you can see, using the parent modules distinguishes the two `Result` types. If instead we specified `use std::fmt::Result` and `use std::io::Result`, we’d have two `Result` types in the same scope and Rust wouldn’t know which one we meant when we used `Result`. ### Providing New Names with the `as` Keyword There’s another solution to the problem of bringing two types of the same name into the same scope with `use`: after the path, we can specify `as` and a new local name, or *alias*, for the type. Listing 7-16 shows another way to write the code in Listing 7-15 by renaming one of the two `Result` types using `as`. Filename: src/lib.rs ``` use std::fmt::Result; use std::io::Result as IoResult; fn function1() -> Result { // --snip-- Ok(()) } fn function2() -> IoResult<()> { // --snip-- Ok(()) } ``` Listing 7-16: Renaming a type when it’s brought into scope with the `as` keyword In the second `use` statement, we chose the new name `IoResult` for the `std::io::Result` type, which won’t conflict with the `Result` from `std::fmt` that we’ve also brought into scope. Listing 7-15 and Listing 7-16 are considered idiomatic, so the choice is up to you! ### Re-exporting Names with `pub use` When we bring a name into scope with the `use` keyword, the name available in the new scope is private. To enable the code that calls our code to refer to that name as if it had been defined in that code’s scope, we can combine `pub` and `use`. This technique is called *re-exporting* because we’re bringing an item into scope but also making that item available for others to bring into their scope. Listing 7-17 shows the code in Listing 7-11 with `use` in the root module changed to `pub use`. Filename: src/lib.rs ``` mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} } } pub use crate::front_of_house::hosting; pub fn eat_at_restaurant() { hosting::add_to_waitlist(); } ``` Listing 7-17: Making a name available for any code to use from a new scope with `pub use` Before this change, external code would have to call the `add_to_waitlist` function by using the path `restaurant::front_of_house::hosting::add_to_waitlist()`. Now that this `pub use` has re-exported the `hosting` module from the root module, external code can now use the path `restaurant::hosting::add_to_waitlist()` instead. Re-exporting is useful when the internal structure of your code is different from how programmers calling your code would think about the domain. For example, in this restaurant metaphor, the people running the restaurant think about “front of house” and “back of house.” But customers visiting a restaurant probably won’t think about the parts of the restaurant in those terms. With `pub use`, we can write our code with one structure but expose a different structure. Doing so makes our library well organized for programmers working on the library and programmers calling the library. We’ll look at another example of `pub use` and how it affects your crate’s documentation in the [“Exporting a Convenient Public API with `pub use`”](ch14-02-publishing-to-crates-io#exporting-a-convenient-public-api-with-pub-use) section of Chapter 14. ### Using External Packages In Chapter 2, we programmed a guessing game project that used an external package called `rand` to get random numbers. To use `rand` in our project, we added this line to *Cargo.toml*: Filename: Cargo.toml ``` rand = "0.8.3" ``` Adding `rand` as a dependency in *Cargo.toml* tells Cargo to download the `rand` package and any dependencies from [crates.io](https://crates.io/) and make `rand` available to our project. Then, to bring `rand` definitions into the scope of our package, we added a `use` line starting with the name of the crate, `rand`, and listed the items we wanted to bring into scope. Recall that in the [“Generating a Random Number”](ch02-00-guessing-game-tutorial#generating-a-random-number) section in Chapter 2, we brought the `Rng` trait into scope and called the `rand::thread_rng` function: ``` use std::io; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } ``` Members of the Rust community have made many packages available at [crates.io](https://crates.io/), and pulling any of them into your package involves these same steps: listing them in your package’s *Cargo.toml* file and using `use` to bring items from their crates into scope. Note that the standard `std` library is also a crate that’s external to our package. Because the standard library is shipped with the Rust language, we don’t need to change *Cargo.toml* to include `std`. But we do need to refer to it with `use` to bring items from there into our package’s scope. For example, with `HashMap` we would use this line: ``` #![allow(unused)] fn main() { use std::collections::HashMap; } ``` This is an absolute path starting with `std`, the name of the standard library crate. ### Using Nested Paths to Clean Up Large `use` Lists If we’re using multiple items defined in the same crate or same module, listing each item on its own line can take up a lot of vertical space in our files. For example, these two `use` statements we had in the Guessing Game in Listing 2-4 bring items from `std` into scope: Filename: src/main.rs ``` use rand::Rng; // --snip-- use std::cmp::Ordering; use std::io; // --snip-- fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), } } ``` Instead, we can use nested paths to bring the same items into scope in one line. We do this by specifying the common part of the path, followed by two colons, and then curly brackets around a list of the parts of the paths that differ, as shown in Listing 7-18. Filename: src/main.rs ``` use rand::Rng; // --snip-- use std::{cmp::Ordering, io}; // --snip-- fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = guess.trim().parse().expect("Please type a number!"); println!("You guessed: {guess}"); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), } } ``` Listing 7-18: Specifying a nested path to bring multiple items with the same prefix into scope In bigger programs, bringing many items into scope from the same crate or module using nested paths can reduce the number of separate `use` statements needed by a lot! We can use a nested path at any level in a path, which is useful when combining two `use` statements that share a subpath. For example, Listing 7-19 shows two `use` statements: one that brings `std::io` into scope and one that brings `std::io::Write` into scope. Filename: src/lib.rs ``` use std::io; use std::io::Write; ``` Listing 7-19: Two `use` statements where one is a subpath of the other The common part of these two paths is `std::io`, and that’s the complete first path. To merge these two paths into one `use` statement, we can use `self` in the nested path, as shown in Listing 7-20. Filename: src/lib.rs ``` use std::io::{self, Write}; ``` Listing 7-20: Combining the paths in Listing 7-19 into one `use` statement This line brings `std::io` and `std::io::Write` into scope. ### The Glob Operator If we want to bring *all* public items defined in a path into scope, we can specify that path followed by the `*` glob operator: ``` #![allow(unused)] fn main() { use std::collections::*; } ``` This `use` statement brings all public items defined in `std::collections` into the current scope. Be careful when using the glob operator! Glob can make it harder to tell what names are in scope and where a name used in your program was defined. The glob operator is often used when testing to bring everything under test into the `tests` module; we’ll talk about that in the [“How to Write Tests”](ch11-01-writing-tests#how-to-write-tests) section in Chapter 11. The glob operator is also sometimes used as part of the prelude pattern: see [the standard library documentation](../std/prelude/index#other-preludes) for more information on that pattern.
programming_docs
rust Variables and Mutability Variables and Mutability ======================== As mentioned in the [“Storing Values with Variables”](ch02-00-guessing-game-tutorial#storing-values-with-variables) section, by default variables are immutable. This is one of many nudges Rust gives you to write your code in a way that takes advantage of the safety and easy concurrency that Rust offers. However, you still have the option to make your variables mutable. Let’s explore how and why Rust encourages you to favor immutability and why sometimes you might want to opt out. When a variable is immutable, once a value is bound to a name, you can’t change that value. To illustrate this, let’s generate a new project called *variables* in your *projects* directory by using `cargo new variables`. Then, in your new *variables* directory, open *src/main.rs* and replace its code with the following code. This code won’t compile just yet, we’ll first examine the immutability error. Filename: src/main.rs ``` fn main() { let x = 5; println!("The value of x is: {x}"); x = 6; println!("The value of x is: {x}"); } ``` Save and run the program using `cargo run`. You should receive an error message, as shown in this output: ``` $ cargo run Compiling variables v0.1.0 (file:///projects/variables) error[E0384]: cannot assign twice to immutable variable `x` --> src/main.rs:4:5 | 2 | let x = 5; | - | | | first assignment to `x` | help: consider making this binding mutable: `mut x` 3 | println!("The value of x is: {x}"); 4 | x = 6; | ^^^^^ cannot assign twice to immutable variable For more information about this error, try `rustc --explain E0384`. error: could not compile `variables` due to previous error ``` This example shows how the compiler helps you find errors in your programs. Compiler errors can be frustrating, but really they only mean your program isn’t safely doing what you want it to do yet; they do *not* mean that you’re not a good programmer! Experienced Rustaceans still get compiler errors. The error message indicates that the cause of the error is that you `cannot assign twice to immutable variable `x``, because you tried to assign a second value to the immutable `x` variable. It’s important that we get compile-time errors when we attempt to change a value that’s designated as immutable because this very situation can lead to bugs. If one part of our code operates on the assumption that a value will never change and another part of our code changes that value, it’s possible that the first part of the code won’t do what it was designed to do. The cause of this kind of bug can be difficult to track down after the fact, especially when the second piece of code changes the value only *sometimes*. The Rust compiler guarantees that when you state a value won’t change, it really won’t change, so you don’t have to keep track of it yourself. Your code is thus easier to reason through. But mutability can be very useful, and can make code more convenient to write. Although variables are immutable by default, you can make them mutable by adding `mut` in front of the variable name as you did in Chapter 2. Adding `mut` also conveys intent to future readers of the code by indicating that other parts of the code will be changing this variable’s value. For example, let’s change *src/main.rs* to the following: Filename: src/main.rs ``` fn main() { let mut x = 5; println!("The value of x is: {x}"); x = 6; println!("The value of x is: {x}"); } ``` When we run the program now, we get this: ``` $ cargo run Compiling variables v0.1.0 (file:///projects/variables) Finished dev [unoptimized + debuginfo] target(s) in 0.30s Running `target/debug/variables` The value of x is: 5 The value of x is: 6 ``` We’re allowed to change the value bound to `x` from `5` to `6` when `mut` is used. Ultimately, deciding whether to use mutability or not is up to you and depends on what you think is clearest in that particular situation. ### Constants Like immutable variables, *constants* are values that are bound to a name and are not allowed to change, but there are a few differences between constants and variables. First, you aren’t allowed to use `mut` with constants. Constants aren’t just immutable by default—they’re always immutable. You declare constants using the `const` keyword instead of the `let` keyword, and the type of the value *must* be annotated. We’re about to cover types and type annotations in the next section, [“Data Types,”](ch03-02-data-types#data-types) so don’t worry about the details right now. Just know that you must always annotate the type. Constants can be declared in any scope, including the global scope, which makes them useful for values that many parts of code need to know about. The last difference is that constants may be set only to a constant expression, not the result of a value that could only be computed at runtime. Here’s an example of a constant declaration: ``` #![allow(unused)] fn main() { const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3; } ``` The constant’s name is `THREE_HOURS_IN_SECONDS` and its value is set to the result of multiplying 60 (the number of seconds in a minute) by 60 (the number of minutes in an hour) by 3 (the number of hours we want to count in this program). Rust’s naming convention for constants is to use all uppercase with underscores between words. The compiler is able to evaluate a limited set of operations at compile time, which lets us choose to write out this value in a way that’s easier to understand and verify, rather than setting this constant to the value 10,800. See the [Rust Reference’s section on constant evaluation](../reference/const_eval) for more information on what operations can be used when declaring constants. Constants are valid for the entire time a program runs, within the scope they were declared in. This property makes constants useful for values in your application domain that multiple parts of the program might need to know about, such as the maximum number of points any player of a game is allowed to earn or the speed of light. Naming hardcoded values used throughout your program as constants is useful in conveying the meaning of that value to future maintainers of the code. It also helps to have only one place in your code you would need to change if the hardcoded value needed to be updated in the future. ### Shadowing As you saw in the guessing game tutorial in [Chapter 2](ch02-00-guessing-game-tutorial#comparing-the-guess-to-the-secret-number), you can declare a new variable with the same name as a previous variable. Rustaceans say that the first variable is *shadowed* by the second, which means that the second variable is what the compiler will see when you use the name of the variable. In effect, the second variable overshadows the first, taking any uses of the variable name to itself until either it itself is shadowed or the scope ends. We can shadow a variable by using the same variable’s name and repeating the use of the `let` keyword as follows: Filename: src/main.rs ``` fn main() { let x = 5; let x = x + 1; { let x = x * 2; println!("The value of x in the inner scope is: {x}"); } println!("The value of x is: {x}"); } ``` This program first binds `x` to a value of `5`. Then it creates a new variable `x` by repeating `let x =`, taking the original value and adding `1` so the value of `x` is then `6`. Then, within an inner scope created with the curly brackets, the third `let` statement also shadows `x` and creates a new variable, multiplying the previous value by `2` to give `x` a value of `12`. When that scope is over, the inner shadowing ends and `x` returns to being `6`. When we run this program, it will output the following: ``` $ cargo run Compiling variables v0.1.0 (file:///projects/variables) Finished dev [unoptimized + debuginfo] target(s) in 0.31s Running `target/debug/variables` The value of x in the inner scope is: 12 The value of x is: 6 ``` Shadowing is different from marking a variable as `mut`, because we’ll get a compile-time error if we accidentally try to reassign to this variable without using the `let` keyword. By using `let`, we can perform a few transformations on a value but have the variable be immutable after those transformations have been completed. The other difference between `mut` and shadowing is that because we’re effectively creating a new variable when we use the `let` keyword again, we can change the type of the value but reuse the same name. For example, say our program asks a user to show how many spaces they want between some text by inputting space characters, and then we want to store that input as a number: ``` fn main() { let spaces = " "; let spaces = spaces.len(); } ``` The first `spaces` variable is a string type and the second `spaces` variable is a number type. Shadowing thus spares us from having to come up with different names, such as `spaces_str` and `spaces_num`; instead, we can reuse the simpler `spaces` name. However, if we try to use `mut` for this, as shown here, we’ll get a compile-time error: ``` fn main() { let mut spaces = " "; spaces = spaces.len(); } ``` The error says we’re not allowed to mutate a variable’s type: ``` $ cargo run Compiling variables v0.1.0 (file:///projects/variables) error[E0308]: mismatched types --> src/main.rs:3:14 | 2 | let mut spaces = " "; | ----- expected due to this value 3 | spaces = spaces.len(); | ^^^^^^^^^^^^ expected `&str`, found `usize` For more information about this error, try `rustc --explain E0308`. error: could not compile `variables` due to previous error ``` Now that we’ve explored how variables work, let’s look at more data types they can have. rust Smart Pointers Smart Pointers ============== A *pointer* is a general concept for a variable that contains an address in memory. This address refers to, or “points at,” some other data. The most common kind of pointer in Rust is a reference, which you learned about in Chapter 4. References are indicated by the `&` symbol and borrow the value they point to. They don’t have any special capabilities other than referring to data, and have no overhead. *Smart pointers*, on the other hand, are data structures that act like a pointer but also have additional metadata and capabilities. The concept of smart pointers isn’t unique to Rust: smart pointers originated in C++ and exist in other languages as well. Rust has a variety of smart pointers defined in the standard library that provide functionality beyond that provided by references. To explore the general concept, we'll look at a couple of different examples of smart pointers, including a *reference counting* smart pointer type. This pointer enables you to allow data to have multiple owners by keeping track of the number of owners and, when no owners remain, cleaning up the data. Rust, with its concept of ownership and borrowing, has an additional difference between references and smart pointers: while references only borrow data, in many cases, smart pointers *own* the data they point to. Though we didn't call them as such at the time, we’ve already encountered a few smart pointers in this book, including `String` and `Vec<T>` in Chapter 8. Both these types count as smart pointers because they own some memory and allow you to manipulate it. They also have metadata and extra capabilities or guarantees. `String`, for example, stores its capacity as metadata and has the extra ability to ensure its data will always be valid UTF-8. Smart pointers are usually implemented using structs. Unlike an ordinary struct, smart pointers implement the `Deref` and `Drop` traits. The `Deref` trait allows an instance of the smart pointer struct to behave like a reference so you can write your code to work with either references or smart pointers. The `Drop` trait allows you to customize the code that's run when an instance of the smart pointer goes out of scope. In this chapter, we’ll discuss both traits and demonstrate why they’re important to smart pointers. Given that the smart pointer pattern is a general design pattern used frequently in Rust, this chapter won’t cover every existing smart pointer. Many libraries have their own smart pointers, and you can even write your own. We’ll cover the most common smart pointers in the standard library: * `Box<T>` for allocating values on the heap * `Rc<T>`, a reference counting type that enables multiple ownership * `Ref<T>` and `RefMut<T>`, accessed through `RefCell<T>`, a type that enforces the borrowing rules at runtime instead of compile time In addition, we’ll cover the *interior mutability* pattern where an immutable type exposes an API for mutating an interior value. We’ll also discuss *reference cycles*: how they can leak memory and how to prevent them. Let’s dive in! rust Accepting Command Line Arguments Accepting Command Line Arguments ================================ Let’s create a new project with, as always, `cargo new`. We’ll call our project `minigrep` to distinguish it from the `grep` tool that you might already have on your system. ``` $ cargo new minigrep Created binary (application) `minigrep` project $ cd minigrep ``` The first task is to make `minigrep` accept its two command line arguments: the file path and a string to search for. That is, we want to be able to run our program with `cargo run`, two hyphens to indicate the following arguments are for our program rather than for `cargo`, a string to search for, and a path to a file to search in, like so: ``` $ cargo run -- searchstring example-filename.txt ``` Right now, the program generated by `cargo new` cannot process arguments we give it. Some existing libraries on [crates.io](https://crates.io/) can help with writing a program that accepts command line arguments, but because you’re just learning this concept, let’s implement this capability ourselves. ### Reading the Argument Values To enable `minigrep` to read the values of command line arguments we pass to it, we’ll need the `std::env::args` function provided in Rust’s standard library. This function returns an iterator of the command line arguments passed to `minigrep`. We’ll cover iterators fully in [Chapter 13](ch13-00-functional-features). For now, you only need to know two details about iterators: iterators produce a series of values, and we can call the `collect` method on an iterator to turn it into a collection, such as a vector, that contains all the elements the iterator produces. The code in Listing 12-1 allows your `minigrep` program to read any command line arguments passed to it and then collect the values into a vector. Filename: src/main.rs ``` use std::env; fn main() { let args: Vec<String> = env::args().collect(); dbg!(args); } ``` Listing 12-1: Collecting the command line arguments into a vector and printing them First, we bring the `std::env` module into scope with a `use` statement so we can use its `args` function. Notice that the `std::env::args` function is nested in two levels of modules. As we discussed in [Chapter 7](ch07-04-bringing-paths-into-scope-with-the-use-keyword#creating-idiomatic-use-paths), in cases where the desired function is nested in more than one module, we’ve chosen to bring the parent module into scope rather than the function. By doing so, we can easily use other functions from `std::env`. It’s also less ambiguous than adding `use std::env::args` and then calling the function with just `args`, because `args` might easily be mistaken for a function that’s defined in the current module. > ### The `args` Function and Invalid Unicode > > Note that `std::env::args` will panic if any argument contains invalid Unicode. If your program needs to accept arguments containing invalid Unicode, use `std::env::args_os` instead. That function returns an iterator that produces `OsString` values instead of `String` values. We’ve chosen to use `std::env::args` here for simplicity, because `OsString` values differ per platform and are more complex to work with than `String` values. > > On the first line of `main`, we call `env::args`, and we immediately use `collect` to turn the iterator into a vector containing all the values produced by the iterator. We can use the `collect` function to create many kinds of collections, so we explicitly annotate the type of `args` to specify that we want a vector of strings. Although we very rarely need to annotate types in Rust, `collect` is one function you do often need to annotate because Rust isn’t able to infer the kind of collection you want. Finally, we print the vector using the debug macro. Let’s try running the code first with no arguments and then with two arguments: ``` $ cargo run Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished dev [unoptimized + debuginfo] target(s) in 0.61s Running `target/debug/minigrep` [src/main.rs:5] args = [ "target/debug/minigrep", ] ``` ``` $ cargo run -- needle haystack Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished dev [unoptimized + debuginfo] target(s) in 1.57s Running `target/debug/minigrep needle haystack` [src/main.rs:5] args = [ "target/debug/minigrep", "needle", "haystack", ] ``` Notice that the first value in the vector is `"target/debug/minigrep"`, which is the name of our binary. This matches the behavior of the arguments list in C, letting programs use the name by which they were invoked in their execution. It’s often convenient to have access to the program name in case you want to print it in messages or change behavior of the program based on what command line alias was used to invoke the program. But for the purposes of this chapter, we’ll ignore it and save only the two arguments we need. ### Saving the Argument Values in Variables The program is currently able to access the values specified as command line arguments. Now we need to save the values of the two arguments in variables so we can use the values throughout the rest of the program. We do that in Listing 12-2. Filename: src/main.rs ``` use std::env; fn main() { let args: Vec<String> = env::args().collect(); let query = &args[1]; let file_path = &args[2]; println!("Searching for {}", query); println!("In file {}", file_path); } ``` Listing 12-2: Creating variables to hold the query argument and file path argument As we saw when we printed the vector, the program’s name takes up the first value in the vector at `args[0]`, so we’re starting arguments at index `1`. The first argument `minigrep` takes is the string we’re searching for, so we put a reference to the first argument in the variable `query`. The second argument will be the file path, so we put a reference to the second argument in the variable `file_path`. We temporarily print the values of these variables to prove that the code is working as we intend. Let’s run this program again with the arguments `test` and `sample.txt`: ``` $ cargo run -- test sample.txt Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished dev [unoptimized + debuginfo] target(s) in 0.0s Running `target/debug/minigrep test sample.txt` Searching for test In file sample.txt ``` Great, the program is working! The values of the arguments we need are being saved into the right variables. Later we’ll add some error handling to deal with certain potential erroneous situations, such as when the user provides no arguments; for now, we’ll ignore that situation and work on adding file-reading capabilities instead. rust Extending Cargo with Custom Commands Extending Cargo with Custom Commands ==================================== Cargo is designed so you can extend it with new subcommands without having to modify Cargo. If a binary in your `$PATH` is named `cargo-something`, you can run it as if it was a Cargo subcommand by running `cargo something`. Custom commands like this are also listed when you run `cargo --list`. Being able to use `cargo install` to install extensions and then run them just like the built-in Cargo tools is a super convenient benefit of Cargo’s design! Summary ------- Sharing code with Cargo and [crates.io](https://crates.io/) is part of what makes the Rust ecosystem useful for many different tasks. Rust’s standard library is small and stable, but crates are easy to share, use, and improve on a timeline different from that of the language. Don’t be shy about sharing code that’s useful to you on [crates.io](https://crates.io/); it’s likely that it will be useful to someone else as well!
programming_docs
rust Storing Lists of Values with Vectors Storing Lists of Values with Vectors ==================================== The first collection type we’ll look at is `Vec<T>`, also known as a *vector*. Vectors allow you to store more than one value in a single data structure that puts all the values next to each other in memory. Vectors can only store values of the same type. They are useful when you have a list of items, such as the lines of text in a file or the prices of items in a shopping cart. ### Creating a New Vector To create a new empty vector, we call the `Vec::new` function, as shown in Listing 8-1. ``` fn main() { let v: Vec<i32> = Vec::new(); } ``` Listing 8-1: Creating a new, empty vector to hold values of type `i32` Note that we added a type annotation here. Because we aren’t inserting any values into this vector, Rust doesn’t know what kind of elements we intend to store. This is an important point. Vectors are implemented using generics; we’ll cover how to use generics with your own types in Chapter 10. For now, know that the `Vec<T>` type provided by the standard library can hold any type. When we create a vector to hold a specific type, we can specify the type within angle brackets. In Listing 8-1, we’ve told Rust that the `Vec<T>` in `v` will hold elements of the `i32` type. More often, you’ll create a `Vec<T>` with initial values and Rust will infer the type of value you want to store, so you rarely need to do this type annotation. Rust conveniently provides the `vec!` macro, which will create a new vector that holds the values you give it. Listing 8-2 creates a new `Vec<i32>` that holds the values `1`, `2`, and `3`. The integer type is `i32` because that’s the default integer type, as we discussed in the [“Data Types”](ch03-02-data-types#data-types) section of Chapter 3. ``` fn main() { let v = vec![1, 2, 3]; } ``` Listing 8-2: Creating a new vector containing values Because we’ve given initial `i32` values, Rust can infer that the type of `v` is `Vec<i32>`, and the type annotation isn’t necessary. Next, we’ll look at how to modify a vector. ### Updating a Vector To create a vector and then add elements to it, we can use the `push` method, as shown in Listing 8-3. ``` fn main() { let mut v = Vec::new(); v.push(5); v.push(6); v.push(7); v.push(8); } ``` Listing 8-3: Using the `push` method to add values to a vector As with any variable, if we want to be able to change its value, we need to make it mutable using the `mut` keyword, as discussed in Chapter 3. The numbers we place inside are all of type `i32`, and Rust infers this from the data, so we don’t need the `Vec<i32>` annotation. ### Reading Elements of Vectors There are two ways to reference a value stored in a vector: via indexing or using the `get` method. In the following examples, we’ve annotated the types of the values that are returned from these functions for extra clarity. Listing 8-4 shows both methods of accessing a value in a vector, with indexing syntax and the `get` method. ``` fn main() { let v = vec![1, 2, 3, 4, 5]; let third: &i32 = &v[2]; println!("The third element is {}", third); let third: Option<&i32> = v.get(2); match third { Some(third) => println!("The third element is {}", third), None => println!("There is no third element."), } } ``` Listing 8-4: Using indexing syntax or the `get` method to access an item in a vector Note a few details here. We use the index value of `2` to get the third element because vectors are indexed by number, starting at zero. Using `&` and `[]` gives us a reference to the element at the index value. When we use the `get` method with the index passed as an argument, we get an `Option<&T>` that we can use with `match`. The reason Rust provides these two ways to reference an element is so you can choose how the program behaves when you try to use an index value outside the range of existing elements. As an example, let’s see what happens when we have a vector of five elements and then we try to access an element at index 100 with each technique, as shown in Listing 8-5. ``` fn main() { let v = vec![1, 2, 3, 4, 5]; let does_not_exist = &v[100]; let does_not_exist = v.get(100); } ``` Listing 8-5: Attempting to access the element at index 100 in a vector containing five elements When we run this code, the first `[]` method will cause the program to panic because it references a nonexistent element. This method is best used when you want your program to crash if there’s an attempt to access an element past the end of the vector. When the `get` method is passed an index that is outside the vector, it returns `None` without panicking. You would use this method if accessing an element beyond the range of the vector may happen occasionally under normal circumstances. Your code will then have logic to handle having either `Some(&element)` or `None`, as discussed in Chapter 6. For example, the index could be coming from a person entering a number. If they accidentally enter a number that’s too large and the program gets a `None` value, you could tell the user how many items are in the current vector and give them another chance to enter a valid value. That would be more user-friendly than crashing the program due to a typo! When the program has a valid reference, the borrow checker enforces the ownership and borrowing rules (covered in Chapter 4) to ensure this reference and any other references to the contents of the vector remain valid. Recall the rule that states you can’t have mutable and immutable references in the same scope. That rule applies in Listing 8-6, where we hold an immutable reference to the first element in a vector and try to add an element to the end. This program won’t work if we also try to refer to that element later in the function: ``` fn main() { let mut v = vec![1, 2, 3, 4, 5]; let first = &v[0]; v.push(6); println!("The first element is: {}", first); } ``` Listing 8-6: Attempting to add an element to a vector while holding a reference to an item Compiling this code will result in this error: ``` $ cargo run Compiling collections v0.1.0 (file:///projects/collections) error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable --> src/main.rs:6:5 | 4 | let first = &v[0]; | - immutable borrow occurs here 5 | 6 | v.push(6); | ^^^^^^^^^ mutable borrow occurs here 7 | 8 | println!("The first element is: {}", first); | ----- immutable borrow later used here For more information about this error, try `rustc --explain E0502`. error: could not compile `collections` due to previous error ``` The code in Listing 8-6 might look like it should work: why should a reference to the first element care about changes at the end of the vector? This error is due to the way vectors work: because vectors put the values next to each other in memory, adding a new element onto the end of the vector might require allocating new memory and copying the old elements to the new space, if there isn’t enough room to put all the elements next to each other where the vector is currently stored. In that case, the reference to the first element would be pointing to deallocated memory. The borrowing rules prevent programs from ending up in that situation. > Note: For more on the implementation details of the `Vec<T>` type, see [“The Rustonomicon”](https://doc.rust-lang.org/nomicon/vec/vec.html). > > ### Iterating over the Values in a Vector To access each element in a vector in turn, we would iterate through all of the elements rather than use indices to access one at a time. Listing 8-7 shows how to use a `for` loop to get immutable references to each element in a vector of `i32` values and print them. ``` fn main() { let v = vec![100, 32, 57]; for i in &v { println!("{}", i); } } ``` Listing 8-7: Printing each element in a vector by iterating over the elements using a `for` loop We can also iterate over mutable references to each element in a mutable vector in order to make changes to all the elements. The `for` loop in Listing 8-8 will add `50` to each element. ``` fn main() { let mut v = vec![100, 32, 57]; for i in &mut v { *i += 50; } } ``` Listing 8-8: Iterating over mutable references to elements in a vector To change the value that the mutable reference refers to, we have to use the `*` dereference operator to get to the value in `i` before we can use the `+=` operator. We’ll talk more about the dereference operator in the [“Following the Pointer to the Value with the Dereference Operator”](ch15-02-deref#following-the-pointer-to-the-value-with-the-dereference-operator) section of Chapter 15. Iterating over a vector, whether immutably or mutably, is safe because of the borrow checker's rules. If we attempted to insert or remove items in the `for` loop bodies in Listing 8-7 and Listing 8-8, we would get a compiler error similar to the one we got with the code in Listing 8-6. The reference to the vector that the `for` loop holds prevents simultaneous modification of the whole vector. ### Using an Enum to Store Multiple Types Vectors can only store values that are the same type. This can be inconvenient; there are definitely use cases for needing to store a list of items of different types. Fortunately, the variants of an enum are defined under the same enum type, so when we need one type to represent elements of different types, we can define and use an enum! For example, say we want to get values from a row in a spreadsheet in which some of the columns in the row contain integers, some floating-point numbers, and some strings. We can define an enum whose variants will hold the different value types, and all the enum variants will be considered the same type: that of the enum. Then we can create a vector to hold that enum and so, ultimately, holds different types. We’ve demonstrated this in Listing 8-9. ``` fn main() { enum SpreadsheetCell { Int(i32), Float(f64), Text(String), } let row = vec![ SpreadsheetCell::Int(3), SpreadsheetCell::Text(String::from("blue")), SpreadsheetCell::Float(10.12), ]; } ``` Listing 8-9: Defining an `enum` to store values of different types in one vector Rust needs to know what types will be in the vector at compile time so it knows exactly how much memory on the heap will be needed to store each element. We must also be explicit about what types are allowed in this vector. If Rust allowed a vector to hold any type, there would be a chance that one or more of the types would cause errors with the operations performed on the elements of the vector. Using an enum plus a `match` expression means that Rust will ensure at compile time that every possible case is handled, as discussed in Chapter 6. If you don’t know the exhaustive set of types a program will get at runtime to store in a vector, the enum technique won’t work. Instead, you can use a trait object, which we’ll cover in Chapter 17. Now that we’ve discussed some of the most common ways to use vectors, be sure to review [the API documentation](../std/vec/struct.vec) for all the many useful methods defined on `Vec<T>` by the standard library. For example, in addition to `push`, a `pop` method removes and returns the last element. ### Dropping a Vector Drops Its Elements Like any other `struct`, a vector is freed when it goes out of scope, as annotated in Listing 8-10. ``` fn main() { { let v = vec![1, 2, 3, 4]; // do stuff with v } // <- v goes out of scope and is freed here } ``` Listing 8-10: Showing where the vector and its elements are dropped When the vector gets dropped, all of its contents are also dropped, meaning the integers it holds will be cleaned up. The borrow checker ensures that any references to contents of a vector are only used while the vector itself is valid. Let’s move on to the next collection type: `String`! rust Macros Macros ====== We’ve used macros like `println!` throughout this book, but we haven’t fully explored what a macro is and how it works. The term *macro* refers to a family of features in Rust: *declarative* macros with `macro_rules!` and three kinds of *procedural* macros: * Custom `#[derive]` macros that specify code added with the `derive` attribute used on structs and enums * Attribute-like macros that define custom attributes usable on any item * Function-like macros that look like function calls but operate on the tokens specified as their argument We’ll talk about each of these in turn, but first, let’s look at why we even need macros when we already have functions. ### The Difference Between Macros and Functions Fundamentally, macros are a way of writing code that writes other code, which is known as *metaprogramming*. In Appendix C, we discuss the `derive` attribute, which generates an implementation of various traits for you. We’ve also used the `println!` and `vec!` macros throughout the book. All of these macros *expand* to produce more code than the code you’ve written manually. Metaprogramming is useful for reducing the amount of code you have to write and maintain, which is also one of the roles of functions. However, macros have some additional powers that functions don’t. A function signature must declare the number and type of parameters the function has. Macros, on the other hand, can take a variable number of parameters: we can call `println!("hello")` with one argument or `println!("hello {}", name)` with two arguments. Also, macros are expanded before the compiler interprets the meaning of the code, so a macro can, for example, implement a trait on a given type. A function can’t, because it gets called at runtime and a trait needs to be implemented at compile time. The downside to implementing a macro instead of a function is that macro definitions are more complex than function definitions because you’re writing Rust code that writes Rust code. Due to this indirection, macro definitions are generally more difficult to read, understand, and maintain than function definitions. Another important difference between macros and functions is that you must define macros or bring them into scope *before* you call them in a file, as opposed to functions you can define anywhere and call anywhere. ### Declarative Macros with `macro_rules!` for General Metaprogramming The most widely used form of macros in Rust is the *declarative macro*. These are also sometimes referred to as “macros by example,” “`macro_rules!` macros,” or just plain “macros.” At their core, declarative macros allow you to write something similar to a Rust `match` expression. As discussed in Chapter 6, `match` expressions are control structures that take an expression, compare the resulting value of the expression to patterns, and then run the code associated with the matching pattern. Macros also compare a value to patterns that are associated with particular code: in this situation, the value is the literal Rust source code passed to the macro; the patterns are compared with the structure of that source code; and the code associated with each pattern, when matched, replaces the code passed to the macro. This all happens during compilation. To define a macro, you use the `macro_rules!` construct. Let’s explore how to use `macro_rules!` by looking at how the `vec!` macro is defined. Chapter 8 covered how we can use the `vec!` macro to create a new vector with particular values. For example, the following macro creates a new vector containing three integers: ``` #![allow(unused)] fn main() { let v: Vec<u32> = vec![1, 2, 3]; } ``` We could also use the `vec!` macro to make a vector of two integers or a vector of five string slices. We wouldn’t be able to use a function to do the same because we wouldn’t know the number or type of values up front. Listing 19-28 shows a slightly simplified definition of the `vec!` macro. Filename: src/lib.rs ``` #[macro_export] macro_rules! vec { ( $( $x:expr ),* ) => { { let mut temp_vec = Vec::new(); $( temp_vec.push($x); )* temp_vec } }; } ``` Listing 19-28: A simplified version of the `vec!` macro definition > Note: The actual definition of the `vec!` macro in the standard library includes code to preallocate the correct amount of memory up front. That code is an optimization that we don’t include here to make the example simpler. > > The `#[macro_export]` annotation indicates that this macro should be made available whenever the crate in which the macro is defined is brought into scope. Without this annotation, the macro can’t be brought into scope. We then start the macro definition with `macro_rules!` and the name of the macro we’re defining *without* the exclamation mark. The name, in this case `vec`, is followed by curly brackets denoting the body of the macro definition. The structure in the `vec!` body is similar to the structure of a `match` expression. Here we have one arm with the pattern `( $( $x:expr ),* )`, followed by `=>` and the block of code associated with this pattern. If the pattern matches, the associated block of code will be emitted. Given that this is the only pattern in this macro, there is only one valid way to match; any other pattern will result in an error. More complex macros will have more than one arm. Valid pattern syntax in macro definitions is different than the pattern syntax covered in Chapter 18 because macro patterns are matched against Rust code structure rather than values. Let’s walk through what the pattern pieces in Listing 19-28 mean; for the full macro pattern syntax, see the [Rust Reference](../reference/macros-by-example). First, we use a set of parentheses to encompass the whole pattern. We use a dollar sign (`$`) to declare a variable in the macro system that will contain the Rust code matching the pattern. The dollar sign makes it clear this is a macro variable as opposed to a regular Rust variable. Next comes a set of parentheses that captures values that match the pattern within the parentheses for use in the replacement code. Within `$()` is `$x:expr`, which matches any Rust expression and gives the expression the name `$x`. The comma following `$()` indicates that a literal comma separator character could optionally appear after the code that matches the code in `$()`. The `*` specifies that the pattern matches zero or more of whatever precedes the `*`. When we call this macro with `vec![1, 2, 3];`, the `$x` pattern matches three times with the three expressions `1`, `2`, and `3`. Now let’s look at the pattern in the body of the code associated with this arm: `temp_vec.push()` within `$()*` is generated for each part that matches `$()` in the pattern zero or more times depending on how many times the pattern matches. The `$x` is replaced with each expression matched. When we call this macro with `vec![1, 2, 3];`, the code generated that replaces this macro call will be the following: ``` { let mut temp_vec = Vec::new(); temp_vec.push(1); temp_vec.push(2); temp_vec.push(3); temp_vec } ``` We’ve defined a macro that can take any number of arguments of any type and can generate code to create a vector containing the specified elements. To learn more about how to write macros, consult the online documentation or other resources, such as [“The Little Book of Rust Macros”](https://veykril.github.io/tlborm/) started by Daniel Keep and continued by Lukas Wirth. ### Procedural Macros for Generating Code from Attributes The second form of macros is the *procedural macro*, which acts more like a function (and is a type of procedure). Procedural macros accept some code as an input, operate on that code, and produce some code as an output rather than matching against patterns and replacing the code with other code as declarative macros do. The three kinds of procedural macros are custom derive, attribute-like, and function-like, and all work in a similar fashion. When creating procedural macros, the definitions must reside in their own crate with a special crate type. This is for complex technical reasons that we hope to eliminate in the future. In Listing 19-29, we show how to define a procedural macro, where `some_attribute` is a placeholder for using a specific macro variety. Filename: src/lib.rs ``` use proc_macro; #[some_attribute] pub fn some_name(input: TokenStream) -> TokenStream { } ``` Listing 19-29: An example of defining a procedural macro The function that defines a procedural macro takes a `TokenStream` as an input and produces a `TokenStream` as an output. The `TokenStream` type is defined by the `proc_macro` crate that is included with Rust and represents a sequence of tokens. This is the core of the macro: the source code that the macro is operating on makes up the input `TokenStream`, and the code the macro produces is the output `TokenStream`. The function also has an attribute attached to it that specifies which kind of procedural macro we’re creating. We can have multiple kinds of procedural macros in the same crate. Let’s look at the different kinds of procedural macros. We’ll start with a custom derive macro and then explain the small dissimilarities that make the other forms different. ### How to Write a Custom `derive` Macro Let’s create a crate named `hello_macro` that defines a trait named `HelloMacro` with one associated function named `hello_macro`. Rather than making our users implement the `HelloMacro` trait for each of their types, we’ll provide a procedural macro so users can annotate their type with `#[derive(HelloMacro)]` to get a default implementation of the `hello_macro` function. The default implementation will print `Hello, Macro! My name is TypeName!` where `TypeName` is the name of the type on which this trait has been defined. In other words, we’ll write a crate that enables another programmer to write code like Listing 19-30 using our crate. Filename: src/main.rs ``` use hello_macro::HelloMacro; use hello_macro_derive::HelloMacro; #[derive(HelloMacro)] struct Pancakes; fn main() { Pancakes::hello_macro(); } ``` Listing 19-30: The code a user of our crate will be able to write when using our procedural macro This code will print `Hello, Macro! My name is Pancakes!` when we’re done. The first step is to make a new library crate, like this: ``` $ cargo new hello_macro --lib ``` Next, we’ll define the `HelloMacro` trait and its associated function: Filename: src/lib.rs ``` pub trait HelloMacro { fn hello_macro(); } ``` We have a trait and its function. At this point, our crate user could implement the trait to achieve the desired functionality, like so: ``` use hello_macro::HelloMacro; struct Pancakes; impl HelloMacro for Pancakes { fn hello_macro() { println!("Hello, Macro! My name is Pancakes!"); } } fn main() { Pancakes::hello_macro(); } ``` However, they would need to write the implementation block for each type they wanted to use with `hello_macro`; we want to spare them from having to do this work. Additionally, we can’t yet provide the `hello_macro` function with default implementation that will print the name of the type the trait is implemented on: Rust doesn’t have reflection capabilities, so it can’t look up the type’s name at runtime. We need a macro to generate code at compile time. The next step is to define the procedural macro. At the time of this writing, procedural macros need to be in their own crate. Eventually, this restriction might be lifted. The convention for structuring crates and macro crates is as follows: for a crate named `foo`, a custom derive procedural macro crate is called `foo_derive`. Let’s start a new crate called `hello_macro_derive` inside our `hello_macro` project: ``` $ cargo new hello_macro_derive --lib ``` Our two crates are tightly related, so we create the procedural macro crate within the directory of our `hello_macro` crate. If we change the trait definition in `hello_macro`, we’ll have to change the implementation of the procedural macro in `hello_macro_derive` as well. The two crates will need to be published separately, and programmers using these crates will need to add both as dependencies and bring them both into scope. We could instead have the `hello_macro` crate use `hello_macro_derive` as a dependency and re-export the procedural macro code. However, the way we’ve structured the project makes it possible for programmers to use `hello_macro` even if they don’t want the `derive` functionality. We need to declare the `hello_macro_derive` crate as a procedural macro crate. We’ll also need functionality from the `syn` and `quote` crates, as you’ll see in a moment, so we need to add them as dependencies. Add the following to the *Cargo.toml* file for `hello_macro_derive`: Filename: hello\_macro\_derive/Cargo.toml ``` [lib] proc-macro = true [dependencies] syn = "1.0" quote = "1.0" ``` To start defining the procedural macro, place the code in Listing 19-31 into your *src/lib.rs* file for the `hello_macro_derive` crate. Note that this code won’t compile until we add a definition for the `impl_hello_macro` function. Filename: hello\_macro\_derive/src/lib.rs ``` use proc_macro::TokenStream; use quote::quote; use syn; #[proc_macro_derive(HelloMacro)] pub fn hello_macro_derive(input: TokenStream) -> TokenStream { // Construct a representation of Rust code as a syntax tree // that we can manipulate let ast = syn::parse(input).unwrap(); // Build the trait implementation impl_hello_macro(&ast) } ``` Listing 19-31: Code that most procedural macro crates will require in order to process Rust code Notice that we’ve split the code into the `hello_macro_derive` function, which is responsible for parsing the `TokenStream`, and the `impl_hello_macro` function, which is responsible for transforming the syntax tree: this makes writing a procedural macro more convenient. The code in the outer function (`hello_macro_derive` in this case) will be the same for almost every procedural macro crate you see or create. The code you specify in the body of the inner function (`impl_hello_macro` in this case) will be different depending on your procedural macro’s purpose. We’ve introduced three new crates: `proc_macro`, [`syn`](https://crates.io/crates/syn), and [`quote`](https://crates.io/crates/quote). The `proc_macro` crate comes with Rust, so we didn’t need to add that to the dependencies in *Cargo.toml*. The `proc_macro` crate is the compiler’s API that allows us to read and manipulate Rust code from our code. The `syn` crate parses Rust code from a string into a data structure that we can perform operations on. The `quote` crate turns `syn` data structures back into Rust code. These crates make it much simpler to parse any sort of Rust code we might want to handle: writing a full parser for Rust code is no simple task. The `hello_macro_derive` function will be called when a user of our library specifies `#[derive(HelloMacro)]` on a type. This is possible because we’ve annotated the `hello_macro_derive` function here with `proc_macro_derive` and specified the name `HelloMacro`, which matches our trait name; this is the convention most procedural macros follow. The `hello_macro_derive` function first converts the `input` from a `TokenStream` to a data structure that we can then interpret and perform operations on. This is where `syn` comes into play. The `parse` function in `syn` takes a `TokenStream` and returns a `DeriveInput` struct representing the parsed Rust code. Listing 19-32 shows the relevant parts of the `DeriveInput` struct we get from parsing the `struct Pancakes;` string: ``` DeriveInput { // --snip-- ident: Ident { ident: "Pancakes", span: #0 bytes(95..103) }, data: Struct( DataStruct { struct_token: Struct, fields: Unit, semi_token: Some( Semi ) } ) } ``` Listing 19-32: The `DeriveInput` instance we get when parsing the code that has the macro’s attribute in Listing 19-30 The fields of this struct show that the Rust code we’ve parsed is a unit struct with the `ident` (identifier, meaning the name) of `Pancakes`. There are more fields on this struct for describing all sorts of Rust code; check the [`syn` documentation for `DeriveInput`](https://docs.rs/syn/1.0/syn/struct.DeriveInput.html) for more information. Soon we’ll define the `impl_hello_macro` function, which is where we’ll build the new Rust code we want to include. But before we do, note that the output for our derive macro is also a `TokenStream`. The returned `TokenStream` is added to the code that our crate users write, so when they compile their crate, they’ll get the extra functionality that we provide in the modified `TokenStream`. You might have noticed that we’re calling `unwrap` to cause the `hello_macro_derive` function to panic if the call to the `syn::parse` function fails here. It’s necessary for our procedural macro to panic on errors because `proc_macro_derive` functions must return `TokenStream` rather than `Result` to conform to the procedural macro API. We’ve simplified this example by using `unwrap`; in production code, you should provide more specific error messages about what went wrong by using `panic!` or `expect`. Now that we have the code to turn the annotated Rust code from a `TokenStream` into a `DeriveInput` instance, let’s generate the code that implements the `HelloMacro` trait on the annotated type, as shown in Listing 19-33. Filename: hello\_macro\_derive/src/lib.rs ``` use proc_macro::TokenStream; use quote::quote; use syn; #[proc_macro_derive(HelloMacro)] pub fn hello_macro_derive(input: TokenStream) -> TokenStream { // Construct a representation of Rust code as a syntax tree // that we can manipulate let ast = syn::parse(input).unwrap(); // Build the trait implementation impl_hello_macro(&ast) } fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream { let name = &ast.ident; let gen = quote! { impl HelloMacro for #name { fn hello_macro() { println!("Hello, Macro! My name is {}!", stringify!(#name)); } } }; gen.into() } ``` Listing 19-33: Implementing the `HelloMacro` trait using the parsed Rust code We get an `Ident` struct instance containing the name (identifier) of the annotated type using `ast.ident`. The struct in Listing 19-32 shows that when we run the `impl_hello_macro` function on the code in Listing 19-30, the `ident` we get will have the `ident` field with a value of `"Pancakes"`. Thus, the `name` variable in Listing 19-33 will contain an `Ident` struct instance that, when printed, will be the string `"Pancakes"`, the name of the struct in Listing 19-30. The `quote!` macro lets us define the Rust code that we want to return. The compiler expects something different to the direct result of the `quote!` macro’s execution, so we need to convert it to a `TokenStream`. We do this by calling the `into` method, which consumes this intermediate representation and returns a value of the required `TokenStream` type. The `quote!` macro also provides some very cool templating mechanics: we can enter `#name`, and `quote!` will replace it with the value in the variable `name`. You can even do some repetition similar to the way regular macros work. Check out [the `quote` crate’s docs](https://docs.rs/quote) for a thorough introduction. We want our procedural macro to generate an implementation of our `HelloMacro` trait for the type the user annotated, which we can get by using `#name`. The trait implementation has the one function `hello_macro`, whose body contains the functionality we want to provide: printing `Hello, Macro! My name is` and then the name of the annotated type. The `stringify!` macro used here is built into Rust. It takes a Rust expression, such as `1 + 2`, and at compile time turns the expression into a string literal, such as `"1 + 2"`. This is different than `format!` or `println!`, macros which evaluate the expression and then turn the result into a `String`. There is a possibility that the `#name` input might be an expression to print literally, so we use `stringify!`. Using `stringify!` also saves an allocation by converting `#name` to a string literal at compile time. At this point, `cargo build` should complete successfully in both `hello_macro` and `hello_macro_derive`. Let’s hook up these crates to the code in Listing 19-30 to see the procedural macro in action! Create a new binary project in your *projects* directory using `cargo new pancakes`. We need to add `hello_macro` and `hello_macro_derive` as dependencies in the `pancakes` crate’s *Cargo.toml*. If you’re publishing your versions of `hello_macro` and `hello_macro_derive` to [crates.io](https://crates.io/), they would be regular dependencies; if not, you can specify them as `path` dependencies as follows: ``` hello_macro = { path = "../hello_macro" } hello_macro_derive = { path = "../hello_macro/hello_macro_derive" } ``` Put the code in Listing 19-30 into *src/main.rs*, and run `cargo run`: it should print `Hello, Macro! My name is Pancakes!` The implementation of the `HelloMacro` trait from the procedural macro was included without the `pancakes` crate needing to implement it; the `#[derive(HelloMacro)]` added the trait implementation. Next, let’s explore how the other kinds of procedural macros differ from custom derive macros. ### Attribute-like macros Attribute-like macros are similar to custom derive macros, but instead of generating code for the `derive` attribute, they allow you to create new attributes. They’re also more flexible: `derive` only works for structs and enums; attributes can be applied to other items as well, such as functions. Here’s an example of using an attribute-like macro: say you have an attribute named `route` that annotates functions when using a web application framework: ``` #[route(GET, "/")] fn index() { ``` This `#[route]` attribute would be defined by the framework as a procedural macro. The signature of the macro definition function would look like this: ``` #[proc_macro_attribute] pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream { ``` Here, we have two parameters of type `TokenStream`. The first is for the contents of the attribute: the `GET, "/"` part. The second is the body of the item the attribute is attached to: in this case, `fn index() {}` and the rest of the function’s body. Other than that, attribute-like macros work the same way as custom derive macros: you create a crate with the `proc-macro` crate type and implement a function that generates the code you want! ### Function-like macros Function-like macros define macros that look like function calls. Similarly to `macro_rules!` macros, they’re more flexible than functions; for example, they can take an unknown number of arguments. However, `macro_rules!` macros can be defined only using the match-like syntax we discussed in the section [“Declarative Macros with `macro_rules!` for General Metaprogramming”](#declarative-macros-with-macro_rules-for-general-metaprogramming) earlier. Function-like macros take a `TokenStream` parameter and their definition manipulates that `TokenStream` using Rust code as the other two types of procedural macros do. An example of a function-like macro is an `sql!` macro that might be called like so: ``` let sql = sql!(SELECT * FROM posts WHERE id=1); ``` This macro would parse the SQL statement inside it and check that it’s syntactically correct, which is much more complex processing than a `macro_rules!` macro can do. The `sql!` macro would be defined like this: ``` #[proc_macro] pub fn sql(input: TokenStream) -> TokenStream { ``` This definition is similar to the custom derive macro’s signature: we receive the tokens that are inside the parentheses and return the code we wanted to generate. Summary ------- Whew! Now you have some Rust features in your toolbox that you likely won’t use often, but you’ll know they’re available in very particular circumstances. We’ve introduced several complex topics so that when you encounter them in error message suggestions or in other peoples’ code, you’ll be able to recognize these concepts and syntax. Use this chapter as a reference to guide you to solutions. Next, we’ll put everything we’ve discussed throughout the book into practice and do one more project!
programming_docs
rust Characteristics of Object-Oriented Languages Characteristics of Object-Oriented Languages ============================================ There is no consensus in the programming community about what features a language must have to be considered object-oriented. Rust is influenced by many programming paradigms, including OOP; for example, we explored the features that came from functional programming in Chapter 13. Arguably, OOP languages share certain common characteristics, namely objects, encapsulation, and inheritance. Let’s look at what each of those characteristics means and whether Rust supports it. ### Objects Contain Data and Behavior The book *Design Patterns: Elements of Reusable Object-Oriented Software* by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley Professional, 1994), colloquially referred to as *The Gang of Four* book, is a catalog of object-oriented design patterns. It defines OOP this way: > Object-oriented programs are made up of objects. An *object* packages both data and the procedures that operate on that data. The procedures are typically called *methods* or *operations*. > > Using this definition, Rust is object-oriented: structs and enums have data, and `impl` blocks provide methods on structs and enums. Even though structs and enums with methods aren’t *called* objects, they provide the same functionality, according to the Gang of Four’s definition of objects. ### Encapsulation that Hides Implementation Details Another aspect commonly associated with OOP is the idea of *encapsulation*, which means that the implementation details of an object aren’t accessible to code using that object. Therefore, the only way to interact with an object is through its public API; code using the object shouldn’t be able to reach into the object’s internals and change data or behavior directly. This enables the programmer to change and refactor an object’s internals without needing to change the code that uses the object. We discussed how to control encapsulation in Chapter 7: we can use the `pub` keyword to decide which modules, types, functions, and methods in our code should be public, and by default everything else is private. For example, we can define a struct `AveragedCollection` that has a field containing a vector of `i32` values. The struct can also have a field that contains the average of the values in the vector, meaning the average doesn’t have to be computed on demand whenever anyone needs it. In other words, `AveragedCollection` will cache the calculated average for us. Listing 17-1 has the definition of the `AveragedCollection` struct: Filename: src/lib.rs ``` pub struct AveragedCollection { list: Vec<i32>, average: f64, } ``` Listing 17-1: An `AveragedCollection` struct that maintains a list of integers and the average of the items in the collection The struct is marked `pub` so that other code can use it, but the fields within the struct remain private. This is important in this case because we want to ensure that whenever a value is added or removed from the list, the average is also updated. We do this by implementing `add`, `remove`, and `average` methods on the struct, as shown in Listing 17-2: Filename: src/lib.rs ``` pub struct AveragedCollection { list: Vec<i32>, average: f64, } impl AveragedCollection { pub fn add(&mut self, value: i32) { self.list.push(value); self.update_average(); } pub fn remove(&mut self) -> Option<i32> { let result = self.list.pop(); match result { Some(value) => { self.update_average(); Some(value) } None => None, } } pub fn average(&self) -> f64 { self.average } fn update_average(&mut self) { let total: i32 = self.list.iter().sum(); self.average = total as f64 / self.list.len() as f64; } } ``` Listing 17-2: Implementations of the public methods `add`, `remove`, and `average` on `AveragedCollection` The public methods `add`, `remove`, and `average` are the only ways to access or modify data in an instance of `AveragedCollection`. When an item is added to `list` using the `add` method or removed using the `remove` method, the implementations of each call the private `update_average` method that handles updating the `average` field as well. We leave the `list` and `average` fields private so there is no way for external code to add or remove items to or from the `list` field directly; otherwise, the `average` field might become out of sync when the `list` changes. The `average` method returns the value in the `average` field, allowing external code to read the `average` but not modify it. Because we’ve encapsulated the implementation details of the struct `AveragedCollection`, we can easily change aspects, such as the data structure, in the future. For instance, we could use a `HashSet<i32>` instead of a `Vec<i32>` for the `list` field. As long as the signatures of the `add`, `remove`, and `average` public methods stay the same, code using `AveragedCollection` wouldn’t need to change. If we made `list` public instead, this wouldn’t necessarily be the case: `HashSet<i32>` and `Vec<i32>` have different methods for adding and removing items, so the external code would likely have to change if it were modifying `list` directly. If encapsulation is a required aspect for a language to be considered object-oriented, then Rust meets that requirement. The option to use `pub` or not for different parts of code enables encapsulation of implementation details. ### Inheritance as a Type System and as Code Sharing *Inheritance* is a mechanism whereby an object can inherit elements from another object’s definition, thus gaining the parent object’s data and behavior without you having to define them again. If a language must have inheritance to be an object-oriented language, then Rust is not one. There is no way to define a struct that inherits the parent struct’s fields and method implementations without using a macro. However, if you’re used to having inheritance in your programming toolbox, you can use other solutions in Rust, depending on your reason for reaching for inheritance in the first place. You would choose inheritance for two main reasons. One is for reuse of code: you can implement particular behavior for one type, and inheritance enables you to reuse that implementation for a different type. You can do this in a limited way in Rust code using default trait method implementations, which you saw in Listing 10-14 when we added a default implementation of the `summarize` method on the `Summary` trait. Any type implementing the `Summary` trait would have the `summarize` method available on it without any further code. This is similar to a parent class having an implementation of a method and an inheriting child class also having the implementation of the method. We can also override the default implementation of the `summarize` method when we implement the `Summary` trait, which is similar to a child class overriding the implementation of a method inherited from a parent class. The other reason to use inheritance relates to the type system: to enable a child type to be used in the same places as the parent type. This is also called *polymorphism*, which means that you can substitute multiple objects for each other at runtime if they share certain characteristics. > ### Polymorphism > > To many people, polymorphism is synonymous with inheritance. But it’s actually a more general concept that refers to code that can work with data of multiple types. For inheritance, those types are generally subclasses. > > Rust instead uses generics to abstract over different possible types and trait bounds to impose constraints on what those types must provide. This is sometimes called *bounded parametric polymorphism*. > > Inheritance has recently fallen out of favor as a programming design solution in many programming languages because it’s often at risk of sharing more code than necessary. Subclasses shouldn’t always share all characteristics of their parent class but will do so with inheritance. This can make a program’s design less flexible. It also introduces the possibility of calling methods on subclasses that don’t make sense or that cause errors because the methods don’t apply to the subclass. In addition, some languages will only allow single inheritance (meaning a subclass can only inherit from one class), further restricting the flexibility of a program’s design. For these reasons, Rust takes the different approach of using trait objects instead of inheritance. Let’s look at how trait objects enable polymorphism in Rust. rust Method Syntax Method Syntax ============= *Methods* are similar to functions: we declare them with the `fn` keyword and a name, they can have parameters and a return value, and they contain some code that’s run when the method is called from somewhere else. Unlike functions, methods are defined within the context of a struct (or an enum or a trait object, which we cover in Chapters 6 and 17, respectively), and their first parameter is always `self`, which represents the instance of the struct the method is being called on. ### Defining Methods Let’s change the `area` function that has a `Rectangle` instance as a parameter and instead make an `area` method defined on the `Rectangle` struct, as shown in Listing 5-13. Filename: src/main.rs ``` #[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; println!( "The area of the rectangle is {} square pixels.", rect1.area() ); } ``` Listing 5-13: Defining an `area` method on the `Rectangle` struct To define the function within the context of `Rectangle`, we start an `impl` (implementation) block for `Rectangle`. Everything within this `impl` block will be associated with the `Rectangle` type. Then we move the `area` function within the `impl` curly brackets and change the first (and in this case, only) parameter to be `self` in the signature and everywhere within the body. In `main`, where we called the `area` function and passed `rect1` as an argument, we can instead use *method syntax* to call the `area` method on our `Rectangle` instance. The method syntax goes after an instance: we add a dot followed by the method name, parentheses, and any arguments. In the signature for `area`, we use `&self` instead of `rectangle: &Rectangle`. The `&self` is actually short for `self: &Self`. Within an `impl` block, the type `Self` is an alias for the type that the `impl` block is for. Methods must have a parameter named `self` of type `Self` for their first parameter, so Rust lets you abbreviate this with only the name `self` in the first parameter spot. Note that we still need to use the `&` in front of the `self` shorthand to indicate this method borrows the `Self` instance, just as we did in `rectangle: &Rectangle`. Methods can take ownership of `self`, borrow `self` immutably as we’ve done here, or borrow `self` mutably, just as they can any other parameter. We’ve chosen `&self` here for the same reason we used `&Rectangle` in the function version: we don’t want to take ownership, and we just want to read the data in the struct, not write to it. If we wanted to change the instance that we’ve called the method on as part of what the method does, we’d use `&mut self` as the first parameter. Having a method that takes ownership of the instance by using just `self` as the first parameter is rare; this technique is usually used when the method transforms `self` into something else and you want to prevent the caller from using the original instance after the transformation. The main reason for using methods instead of functions, in addition to providing method syntax and not having to repeat the type of `self` in every method’s signature, is for organization. We’ve put all the things we can do with an instance of a type in one `impl` block rather than making future users of our code search for capabilities of `Rectangle` in various places in the library we provide. Note that we can choose to give a method the same name as one of the struct’s fields. For example, we can define a method on `Rectangle` also named `width`: Filename: src/main.rs ``` #[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn width(&self) -> bool { self.width > 0 } } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; if rect1.width() { println!("The rectangle has a nonzero width; it is {}", rect1.width); } } ``` Here, we’re choosing to make the `width` method return `true` if the value in the instance’s `width` field is greater than 0, and `false` if the value is 0: we can use a field within a method of the same name for any purpose. In `main`, when we follow `rect1.width` with parentheses, Rust knows we mean the method `width`. When we don’t use parentheses, Rust knows we mean the field `width`. Often, but not always, when we give methods with the same name as a field we want it to only return the value in the field and do nothing else. Methods like this are called *getters*, and Rust does not implement them automatically for struct fields as some other languages do. Getters are useful because you can make the field private but the method public and thus enable read-only access to that field as part of the type’s public API. We will be discussing what public and private are and how to designate a field or method as public or private in Chapter 7. > ### Where’s the `->` Operator? > > In C and C++, two different operators are used for calling methods: you use `.` if you’re calling a method on the object directly and `->` if you’re calling the method on a pointer to the object and need to dereference the pointer first. In other words, if `object` is a pointer, `object->something()` is similar to `(*object).something()`. > > Rust doesn’t have an equivalent to the `->` operator; instead, Rust has a feature called *automatic referencing and dereferencing*. Calling methods is one of the few places in Rust that has this behavior. > > Here’s how it works: when you call a method with `object.something()`, Rust automatically adds in `&`, `&mut`, or `*` so `object` matches the signature of the method. In other words, the following are the same: > > > ``` > #![allow(unused)] > fn main() { > #[derive(Debug,Copy,Clone)] > struct Point { > x: f64, > y: f64, > } > > impl Point { > fn distance(&self, other: &Point) -> f64 { > let x_squared = f64::powi(other.x - self.x, 2); > let y_squared = f64::powi(other.y - self.y, 2); > > f64::sqrt(x_squared + y_squared) > } > } > let p1 = Point { x: 0.0, y: 0.0 }; > let p2 = Point { x: 5.0, y: 6.5 }; > p1.distance(&p2); > (&p1).distance(&p2); > } > > ``` > The first one looks much cleaner. This automatic referencing behavior works because methods have a clear receiver—the type of `self`. Given the receiver and name of a method, Rust can figure out definitively whether the method is reading (`&self`), mutating (`&mut self`), or consuming (`self`). The fact that Rust makes borrowing implicit for method receivers is a big part of making ownership ergonomic in practice. > > ### Methods with More Parameters Let’s practice using methods by implementing a second method on the `Rectangle` struct. This time, we want an instance of `Rectangle` to take another instance of `Rectangle` and return `true` if the second `Rectangle` can fit completely within `self` (the first `Rectangle`); otherwise it should return `false`. That is, once we’ve defined the `can_hold` method, we want to be able to write the program shown in Listing 5-14. Filename: src/main.rs ``` fn main() { let rect1 = Rectangle { width: 30, height: 50, }; let rect2 = Rectangle { width: 10, height: 40, }; let rect3 = Rectangle { width: 60, height: 45, }; println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3)); } ``` Listing 5-14: Using the as-yet-unwritten `can_hold` method And the expected output would look like the following, because both dimensions of `rect2` are smaller than the dimensions of `rect1` but `rect3` is wider than `rect1`: ``` Can rect1 hold rect2? true Can rect1 hold rect3? false ``` We know we want to define a method, so it will be within the `impl Rectangle` block. The method name will be `can_hold`, and it will take an immutable borrow of another `Rectangle` as a parameter. We can tell what the type of the parameter will be by looking at the code that calls the method: `rect1.can_hold(&rect2)` passes in `&rect2`, which is an immutable borrow to `rect2`, an instance of `Rectangle`. This makes sense because we only need to read `rect2` (rather than write, which would mean we’d need a mutable borrow), and we want `main` to retain ownership of `rect2` so we can use it again after calling the `can_hold` method. The return value of `can_hold` will be a Boolean, and the implementation will check whether the width and height of `self` are both greater than the width and height of the other `Rectangle`, respectively. Let’s add the new `can_hold` method to the `impl` block from Listing 5-13, shown in Listing 5-15. Filename: src/main.rs ``` #[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; let rect2 = Rectangle { width: 10, height: 40, }; let rect3 = Rectangle { width: 60, height: 45, }; println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3)); } ``` Listing 5-15: Implementing the `can_hold` method on `Rectangle` that takes another `Rectangle` instance as a parameter When we run this code with the `main` function in Listing 5-14, we’ll get our desired output. Methods can take multiple parameters that we add to the signature after the `self` parameter, and those parameters work just like parameters in functions. ### Associated Functions All functions defined within an `impl` block are called *associated functions* because they’re associated with the type named after the `impl`. We can define associated functions that don’t have `self` as their first parameter (and thus are not methods) because they don’t need an instance of the type to work with. We’ve already used one function like this: the `String::from` function that’s defined on the `String` type. Associated functions that aren’t methods are often used for constructors that will return a new instance of the struct. These are often called `new`, but `new` isn’t a special name and isn’t built into the language. For example, we could choose to provide an associated function named `square` that would have one dimension parameter and use that as both width and height, thus making it easier to create a square `Rectangle` rather than having to specify the same value twice: Filename: src/main.rs ``` #[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn square(size: u32) -> Self { Self { width: size, height: size, } } } fn main() { let sq = Rectangle::square(3); } ``` The `Self` keywords in the return type and in the body of the function are aliases for the type that appears after the `impl` keyword, which in this case is `Rectangle`. To call this associated function, we use the `::` syntax with the struct name; `let sq = Rectangle::square(3);` is an example. This function is namespaced by the struct: the `::` syntax is used for both associated functions and namespaces created by modules. We’ll discuss modules in Chapter 7. ### Multiple `impl` Blocks Each struct is allowed to have multiple `impl` blocks. For example, Listing 5-15 is equivalent to the code shown in Listing 5-16, which has each method in its own `impl` block. ``` #[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } } impl Rectangle { fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; let rect2 = Rectangle { width: 10, height: 40, }; let rect3 = Rectangle { width: 60, height: 45, }; println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3)); } ``` Listing 5-16: Rewriting Listing 5-15 using multiple `impl` blocks There’s no reason to separate these methods into multiple `impl` blocks here, but this is valid syntax. We’ll see a case in which multiple `impl` blocks are useful in Chapter 10, where we discuss generic types and traits. Summary ------- Structs let you create custom types that are meaningful for your domain. By using structs, you can keep associated pieces of data connected to each other and name each piece to make your code clear. In `impl` blocks, you can define functions that are associated with your type, and methods are a kind of associated function that let you specify the behavior that instances of your structs have. But structs aren’t the only way you can create custom types: let’s turn to Rust’s enum feature to add another tool to your toolbox.
programming_docs
rust Advanced Features Advanced Features ================= By now, you’ve learned the most commonly used parts of the Rust programming language. Before we do one more project in Chapter 20, we’ll look at a few aspects of the language you might run into every once in a while, but may not use every day. You can use this chapter as a reference for when you encounter any unknowns. The features covered here are useful in very specific situations. Although you might not reach for them often, we want to make sure you have a grasp of all the features Rust has to offer. In this chapter, we’ll cover: * Unsafe Rust: how to opt out of some of Rust’s guarantees and take responsibility for manually upholding those guarantees * Advanced traits: associated types, default type parameters, fully qualified syntax, supertraits, and the newtype pattern in relation to traits * Advanced types: more about the newtype pattern, type aliases, the never type, and dynamically sized types * Advanced functions and closures: function pointers and returning closures * Macros: ways to define code that defines more code at compile time It’s a panoply of Rust features with something for everyone! Let’s dive in! rust Final Project: Building a Multithreaded Web Server Final Project: Building a Multithreaded Web Server ================================================== It’s been a long journey, but we’ve reached the end of the book. In this chapter, we’ll build one more project together to demonstrate some of the concepts we covered in the final chapters, as well as recap some earlier lessons. For our final project, we’ll make a web server that says “hello” and looks like Figure 20-1 in a web browser. Figure 20-1: Our final shared project Here is our plan for building the web server: 1. Learn a bit about TCP and HTTP. 2. Listen for TCP connections on a socket. 3. Parse a small number of HTTP requests. 4. Create a proper HTTP response. 5. Improve the throughput of our server with a thread pool. Before we get started, we should mention one detail: the method we’ll use won’t be the best way to build a web server with Rust. Community members have published a number of production-ready crates available on [crates.io](https://crates.io/) that provide more complete web server and thread pool implementations than we’ll build. However, our intention in this chapter is to help you learn, not to take the easy route. Because Rust is a systems programming language, we can choose the level of abstraction we want to work with and can go to a lower level than is possible or practical in other languages. We’ll therefore write the basic HTTP server and thread pool manually so you can learn the general ideas and techniques behind the crates you might use in the future. rust Appendix G - How Rust is Made and “Nightly Rust” Appendix G - How Rust is Made and “Nightly Rust” ================================================ This appendix is about how Rust is made and how that affects you as a Rust developer. ### Stability Without Stagnation As a language, Rust cares a *lot* about the stability of your code. We want Rust to be a rock-solid foundation you can build on, and if things were constantly changing, that would be impossible. At the same time, if we can’t experiment with new features, we may not find out important flaws until after their release, when we can no longer change things. Our solution to this problem is what we call “stability without stagnation”, and our guiding principle is this: you should never have to fear upgrading to a new version of stable Rust. Each upgrade should be painless, but should also bring you new features, fewer bugs, and faster compile times. ### Choo, Choo! Release Channels and Riding the Trains Rust development operates on a *train schedule*. That is, all development is done on the `master` branch of the Rust repository. Releases follow a software release train model, which has been used by Cisco IOS and other software projects. There are three *release channels* for Rust: * Nightly * Beta * Stable Most Rust developers primarily use the stable channel, but those who want to try out experimental new features may use nightly or beta. Here’s an example of how the development and release process works: let’s assume that the Rust team is working on the release of Rust 1.5. That release happened in December of 2015, but it will provide us with realistic version numbers. A new feature is added to Rust: a new commit lands on the `master` branch. Each night, a new nightly version of Rust is produced. Every day is a release day, and these releases are created by our release infrastructure automatically. So as time passes, our releases look like this, once a night: ``` nightly: * - - * - - * ``` Every six weeks, it’s time to prepare a new release! The `beta` branch of the Rust repository branches off from the `master` branch used by nightly. Now, there are two releases: ``` nightly: * - - * - - * | beta: * ``` Most Rust users do not use beta releases actively, but test against beta in their CI system to help Rust discover possible regressions. In the meantime, there’s still a nightly release every night: ``` nightly: * - - * - - * - - * - - * | beta: * ``` Let’s say a regression is found. Good thing we had some time to test the beta release before the regression snuck into a stable release! The fix is applied to `master`, so that nightly is fixed, and then the fix is backported to the `beta` branch, and a new release of beta is produced: ``` nightly: * - - * - - * - - * - - * - - * | beta: * - - - - - - - - * ``` Six weeks after the first beta was created, it’s time for a stable release! The `stable` branch is produced from the `beta` branch: ``` nightly: * - - * - - * - - * - - * - - * - * - * | beta: * - - - - - - - - * | stable: * ``` Hooray! Rust 1.5 is done! However, we’ve forgotten one thing: because the six weeks have gone by, we also need a new beta of the *next* version of Rust, 1.6. So after `stable` branches off of `beta`, the next version of `beta` branches off of `nightly` again: ``` nightly: * - - * - - * - - * - - * - - * - * - * | | beta: * - - - - - - - - * * | stable: * ``` This is called the “train model” because every six weeks, a release “leaves the station”, but still has to take a journey through the beta channel before it arrives as a stable release. Rust releases every six weeks, like clockwork. If you know the date of one Rust release, you can know the date of the next one: it’s six weeks later. A nice aspect of having releases scheduled every six weeks is that the next train is coming soon. If a feature happens to miss a particular release, there’s no need to worry: another one is happening in a short time! This helps reduce pressure to sneak possibly unpolished features in close to the release deadline. Thanks to this process, you can always check out the next build of Rust and verify for yourself that it’s easy to upgrade to: if a beta release doesn’t work as expected, you can report it to the team and get it fixed before the next stable release happens! Breakage in a beta release is relatively rare, but `rustc` is still a piece of software, and bugs do exist. ### Unstable Features There’s one more catch with this release model: unstable features. Rust uses a technique called “feature flags” to determine what features are enabled in a given release. If a new feature is under active development, it lands on `master`, and therefore, in nightly, but behind a *feature flag*. If you, as a user, wish to try out the work-in-progress feature, you can, but you must be using a nightly release of Rust and annotate your source code with the appropriate flag to opt in. If you’re using a beta or stable release of Rust, you can’t use any feature flags. This is the key that allows us to get practical use with new features before we declare them stable forever. Those who wish to opt into the bleeding edge can do so, and those who want a rock-solid experience can stick with stable and know that their code won’t break. Stability without stagnation. This book only contains information about stable features, as in-progress features are still changing, and surely they’ll be different between when this book was written and when they get enabled in stable builds. You can find documentation for nightly-only features online. ### Rustup and the Role of Rust Nightly Rustup makes it easy to change between different release channels of Rust, on a global or per-project basis. By default, you’ll have stable Rust installed. To install nightly, for example: ``` $ rustup toolchain install nightly ``` You can see all of the *toolchains* (releases of Rust and associated components) you have installed with `rustup` as well. Here’s an example on one of your authors’ Windows computer: ``` > rustup toolchain list stable-x86_64-pc-windows-msvc (default) beta-x86_64-pc-windows-msvc nightly-x86_64-pc-windows-msvc ``` As you can see, the stable toolchain is the default. Most Rust users use stable most of the time. You might want to use stable most of the time, but use nightly on a specific project, because you care about a cutting-edge feature. To do so, you can use `rustup override` in that project’s directory to set the nightly toolchain as the one `rustup` should use when you’re in that directory: ``` $ cd ~/projects/needs-nightly $ rustup override set nightly ``` Now, every time you call `rustc` or `cargo` inside of *~/projects/needs-nightly*, `rustup` will make sure that you are using nightly Rust, rather than your default of stable Rust. This comes in handy when you have a lot of Rust projects! ### The RFC Process and Teams So how do you learn about these new features? Rust’s development model follows a *Request For Comments (RFC) process*. If you’d like an improvement in Rust, you can write up a proposal, called an RFC. Anyone can write RFCs to improve Rust, and the proposals are reviewed and discussed by the Rust team, which is comprised of many topic subteams. There’s a full list of the teams [on Rust’s website](https://www.rust-lang.org/governance), which includes teams for each area of the project: language design, compiler implementation, infrastructure, documentation, and more. The appropriate team reads the proposal and the comments, writes some comments of their own, and eventually, there’s consensus to accept or reject the feature. If the feature is accepted, an issue is opened on the Rust repository, and someone can implement it. The person who implements it very well may not be the person who proposed the feature in the first place! When the implementation is ready, it lands on the `master` branch behind a feature gate, as we discussed in the [“Unstable Features”](#unstable-features) section. After some time, once Rust developers who use nightly releases have been able to try out the new feature, team members will discuss the feature, how it’s worked out on nightly, and decide if it should make it into stable Rust or not. If the decision is to move forward, the feature gate is removed, and the feature is now considered stable! It rides the trains into a new stable release of Rust. rust The Slice Type The Slice Type ============== *Slices* let you reference a contiguous sequence of elements in a collection rather than the whole collection. A slice is a kind of reference, so it does not have ownership. Here’s a small programming problem: write a function that takes a string of words separated by spaces and returns the first word it finds in that string. If the function doesn’t find a space in the string, the whole string must be one word, so the entire string should be returned. Let’s work through how we’d write the signature of this function without using slices, to understand the problem that slices will solve: ``` fn first_word(s: &String) -> ? ``` The `first_word` function has a `&String` as a parameter. We don’t want ownership, so this is fine. But what should we return? We don’t really have a way to talk about *part* of a string. However, we could return the index of the end of the word, indicated by a space. Let’s try that, as shown in Listing 4-7. Filename: src/main.rs ``` fn first_word(s: &String) -> usize { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return i; } } s.len() } fn main() {} ``` Listing 4-7: The `first_word` function that returns a byte index value into the `String` parameter Because we need to go through the `String` element by element and check whether a value is a space, we’ll convert our `String` to an array of bytes using the `as_bytes` method: ``` fn first_word(s: &String) -> usize { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return i; } } s.len() } fn main() {} ``` Next, we create an iterator over the array of bytes using the `iter` method: ``` fn first_word(s: &String) -> usize { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return i; } } s.len() } fn main() {} ``` We’ll discuss iterators in more detail in [Chapter 13](ch13-02-iterators). For now, know that `iter` is a method that returns each element in a collection and that `enumerate` wraps the result of `iter` and returns each element as part of a tuple instead. The first element of the tuple returned from `enumerate` is the index, and the second element is a reference to the element. This is a bit more convenient than calculating the index ourselves. Because the `enumerate` method returns a tuple, we can use patterns to destructure that tuple. We’ll be discussing patterns more in [Chapter 6](ch06-02-match#patterns-that-bind-to-values). In the `for` loop, we specify a pattern that has `i` for the index in the tuple and `&item` for the single byte in the tuple. Because we get a reference to the element from `.iter().enumerate()`, we use `&` in the pattern. Inside the `for` loop, we search for the byte that represents the space by using the byte literal syntax. If we find a space, we return the position. Otherwise, we return the length of the string by using `s.len()`: ``` fn first_word(s: &String) -> usize { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return i; } } s.len() } fn main() {} ``` We now have a way to find out the index of the end of the first word in the string, but there’s a problem. We’re returning a `usize` on its own, but it’s only a meaningful number in the context of the `&String`. In other words, because it’s a separate value from the `String`, there’s no guarantee that it will still be valid in the future. Consider the program in Listing 4-8 that uses the `first_word` function from Listing 4-7. Filename: src/main.rs ``` fn first_word(s: &String) -> usize { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return i; } } s.len() } fn main() { let mut s = String::from("hello world"); let word = first_word(&s); // word will get the value 5 s.clear(); // this empties the String, making it equal to "" // word still has the value 5 here, but there's no more string that // we could meaningfully use the value 5 with. word is now totally invalid! } ``` Listing 4-8: Storing the result from calling the `first_word` function and then changing the `String` contents This program compiles without any errors and would also do so if we used `word` after calling `s.clear()`. Because `word` isn’t connected to the state of `s` at all, `word` still contains the value `5`. We could use that value `5` with the variable `s` to try to extract the first word out, but this would be a bug because the contents of `s` have changed since we saved `5` in `word`. Having to worry about the index in `word` getting out of sync with the data in `s` is tedious and error prone! Managing these indices is even more brittle if we write a `second_word` function. Its signature would have to look like this: ``` fn second_word(s: &String) -> (usize, usize) { ``` Now we’re tracking a starting *and* an ending index, and we have even more values that were calculated from data in a particular state but aren’t tied to that state at all. We have three unrelated variables floating around that need to be kept in sync. Luckily, Rust has a solution to this problem: string slices. ### String Slices A *string slice* is a reference to part of a `String`, and it looks like this: ``` fn main() { let s = String::from("hello world"); let hello = &s[0..5]; let world = &s[6..11]; } ``` Rather than a reference to the entire `String`, `hello` is a reference to a portion of the `String`, specified in the extra `[0..5]` bit. We create slices using a range within brackets by specifying `[starting_index..ending_index]`, where `starting_index` is the first position in the slice and `ending_index` is one more than the last position in the slice. Internally, the slice data structure stores the starting position and the length of the slice, which corresponds to `ending_index` minus `starting_index`. So in the case of `let world = &s[6..11];`, `world` would be a slice that contains a pointer to the byte at index 6 of `s` with a length value of 5. Figure 4-6 shows this in a diagram. Figure 4-6: String slice referring to part of a `String` With Rust’s `..` range syntax, if you want to start at index zero, you can drop the value before the two periods. In other words, these are equal: ``` #![allow(unused)] fn main() { let s = String::from("hello"); let slice = &s[0..2]; let slice = &s[..2]; } ``` By the same token, if your slice includes the last byte of the `String`, you can drop the trailing number. That means these are equal: ``` #![allow(unused)] fn main() { let s = String::from("hello"); let len = s.len(); let slice = &s[3..len]; let slice = &s[3..]; } ``` You can also drop both values to take a slice of the entire string. So these are equal: ``` #![allow(unused)] fn main() { let s = String::from("hello"); let len = s.len(); let slice = &s[0..len]; let slice = &s[..]; } ``` > Note: String slice range indices must occur at valid UTF-8 character boundaries. If you attempt to create a string slice in the middle of a multibyte character, your program will exit with an error. For the purposes of introducing string slices, we are assuming ASCII only in this section; a more thorough discussion of UTF-8 handling is in the [“Storing UTF-8 Encoded Text with Strings”](ch08-02-strings#storing-utf-8-encoded-text-with-strings) section of Chapter 8. > > With all this information in mind, let’s rewrite `first_word` to return a slice. The type that signifies “string slice” is written as `&str`: Filename: src/main.rs ``` fn first_word(s: &String) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } fn main() {} ``` We get the index for the end of the word in the same way as we did in Listing 4-7, by looking for the first occurrence of a space. When we find a space, we return a string slice using the start of the string and the index of the space as the starting and ending indices. Now when we call `first_word`, we get back a single value that is tied to the underlying data. The value is made up of a reference to the starting point of the slice and the number of elements in the slice. Returning a slice would also work for a `second_word` function: ``` fn second_word(s: &String) -> &str { ``` We now have a straightforward API that’s much harder to mess up, because the compiler will ensure the references into the `String` remain valid. Remember the bug in the program in Listing 4-8, when we got the index to the end of the first word but then cleared the string so our index was invalid? That code was logically incorrect but didn’t show any immediate errors. The problems would show up later if we kept trying to use the first word index with an emptied string. Slices make this bug impossible and let us know we have a problem with our code much sooner. Using the slice version of `first_word` will throw a compile-time error: Filename: src/main.rs ``` fn first_word(s: &String) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } fn main() { let mut s = String::from("hello world"); let word = first_word(&s); s.clear(); // error! println!("the first word is: {}", word); } ``` Here’s the compiler error: ``` $ cargo run Compiling ownership v0.1.0 (file:///projects/ownership) error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable --> src/main.rs:18:5 | 16 | let word = first_word(&s); | -- immutable borrow occurs here 17 | 18 | s.clear(); // error! | ^^^^^^^^^ mutable borrow occurs here 19 | 20 | println!("the first word is: {}", word); | ---- immutable borrow later used here For more information about this error, try `rustc --explain E0502`. error: could not compile `ownership` due to previous error ``` Recall from the borrowing rules that if we have an immutable reference to something, we cannot also take a mutable reference. Because `clear` needs to truncate the `String`, it needs to get a mutable reference. The `println!` after the call to `clear` uses the reference in `word`, so the immutable reference must still be active at that point. Rust disallows the mutable reference in `clear` and the immutable reference in `word` from existing at the same time, and compilation fails. Not only has Rust made our API easier to use, but it has also eliminated an entire class of errors at compile time! #### String Literals Are Slices Recall that we talked about string literals being stored inside the binary. Now that we know about slices, we can properly understand string literals: ``` #![allow(unused)] fn main() { let s = "Hello, world!"; } ``` The type of `s` here is `&str`: it’s a slice pointing to that specific point of the binary. This is also why string literals are immutable; `&str` is an immutable reference. #### String Slices as Parameters Knowing that you can take slices of literals and `String` values leads us to one more improvement on `first_word`, and that’s its signature: ``` fn first_word(s: &String) -> &str { ``` A more experienced Rustacean would write the signature shown in Listing 4-9 instead because it allows us to use the same function on both `&String` values and `&str` values. ``` fn first_word(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } fn main() { let my_string = String::from("hello world"); // `first_word` works on slices of `String`s, whether partial or whole let word = first_word(&my_string[0..6]); let word = first_word(&my_string[..]); // `first_word` also works on references to `String`s, which are equivalent // to whole slices of `String`s let word = first_word(&my_string); let my_string_literal = "hello world"; // `first_word` works on slices of string literals, whether partial or whole let word = first_word(&my_string_literal[0..6]); let word = first_word(&my_string_literal[..]); // Because string literals *are* string slices already, // this works too, without the slice syntax! let word = first_word(my_string_literal); } ``` Listing 4-9: Improving the `first_word` function by using a string slice for the type of the `s` parameter If we have a string slice, we can pass that directly. If we have a `String`, we can pass a slice of the `String` or a reference to the `String`. This flexibility takes advantage of *deref coercions*, a feature we will cover in the [“Implicit Deref Coercions with Functions and Methods”](ch15-02-deref#implicit-deref-coercions-with-functions-and-methods) section of Chapter 15. Defining a function to take a string slice instead of a reference to a `String` makes our API more general and useful without losing any functionality: Filename: src/main.rs ``` fn first_word(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } fn main() { let my_string = String::from("hello world"); // `first_word` works on slices of `String`s, whether partial or whole let word = first_word(&my_string[0..6]); let word = first_word(&my_string[..]); // `first_word` also works on references to `String`s, which are equivalent // to whole slices of `String`s let word = first_word(&my_string); let my_string_literal = "hello world"; // `first_word` works on slices of string literals, whether partial or whole let word = first_word(&my_string_literal[0..6]); let word = first_word(&my_string_literal[..]); // Because string literals *are* string slices already, // this works too, without the slice syntax! let word = first_word(my_string_literal); } ``` ### Other Slices String slices, as you might imagine, are specific to strings. But there’s a more general slice type, too. Consider this array: ``` #![allow(unused)] fn main() { let a = [1, 2, 3, 4, 5]; } ``` Just as we might want to refer to a part of a string, we might want to refer to part of an array. We’d do so like this: ``` #![allow(unused)] fn main() { let a = [1, 2, 3, 4, 5]; let slice = &a[1..3]; assert_eq!(slice, &[2, 3]); } ``` This slice has the type `&[i32]`. It works the same way as string slices do, by storing a reference to the first element and a length. You’ll use this kind of slice for all sorts of other collections. We’ll discuss these collections in detail when we talk about vectors in Chapter 8. Summary ------- The concepts of ownership, borrowing, and slices ensure memory safety in Rust programs at compile time. The Rust language gives you control over your memory usage in the same way as other systems programming languages, but having the owner of data automatically clean up that data when the owner goes out of scope means you don’t have to write and debug extra code to get this control. Ownership affects how lots of other parts of Rust work, so we’ll talk about these concepts further throughout the rest of the book. Let’s move on to Chapter 5 and look at grouping pieces of data together in a `struct`.
programming_docs
rust Concise Control Flow with if let Concise Control Flow with `if let` ================================== The `if let` syntax lets you combine `if` and `let` into a less verbose way to handle values that match one pattern while ignoring the rest. Consider the program in Listing 6-6 that matches on an `Option<u8>` value in the `config_max` variable but only wants to execute code if the value is the `Some` variant. ``` fn main() { let config_max = Some(3u8); match config_max { Some(max) => println!("The maximum is configured to be {}", max), _ => (), } } ``` Listing 6-6: A `match` that only cares about executing code when the value is `Some` If the value is `Some`, we print out the value in the `Some` variant by binding the value to the variable `max` in the pattern. We don’t want to do anything with the `None` value. To satisfy the `match` expression, we have to add `_ => ()` after processing just one variant, which is annoying boilerplate code to add. Instead, we could write this in a shorter way using `if let`. The following code behaves the same as the `match` in Listing 6-6: ``` fn main() { let config_max = Some(3u8); if let Some(max) = config_max { println!("The maximum is configured to be {}", max); } } ``` The syntax `if let` takes a pattern and an expression separated by an equal sign. It works the same way as a `match`, where the expression is given to the `match` and the pattern is its first arm. In this case, the pattern is `Some(max)`, and the `max` binds to the value inside the `Some`. We can then use `max` in the body of the `if let` block in the same way as we used `max` in the corresponding `match` arm. The code in the `if let` block isn’t run if the value doesn’t match the pattern. Using `if let` means less typing, less indentation, and less boilerplate code. However, you lose the exhaustive checking that `match` enforces. Choosing between `match` and `if let` depends on what you’re doing in your particular situation and whether gaining conciseness is an appropriate trade-off for losing exhaustive checking. In other words, you can think of `if let` as syntax sugar for a `match` that runs code when the value matches one pattern and then ignores all other values. We can include an `else` with an `if let`. The block of code that goes with the `else` is the same as the block of code that would go with the `_` case in the `match` expression that is equivalent to the `if let` and `else`. Recall the `Coin` enum definition in Listing 6-4, where the `Quarter` variant also held a `UsState` value. If we wanted to count all non-quarter coins we see while also announcing the state of the quarters, we could do that with a `match` expression like this: ``` #[derive(Debug)] enum UsState { Alabama, Alaska, // --snip-- } enum Coin { Penny, Nickel, Dime, Quarter(UsState), } fn main() { let coin = Coin::Penny; let mut count = 0; match coin { Coin::Quarter(state) => println!("State quarter from {:?}!", state), _ => count += 1, } } ``` Or we could use an `if let` and `else` expression like this: ``` #[derive(Debug)] enum UsState { Alabama, Alaska, // --snip-- } enum Coin { Penny, Nickel, Dime, Quarter(UsState), } fn main() { let coin = Coin::Penny; let mut count = 0; if let Coin::Quarter(state) = coin { println!("State quarter from {:?}!", state); } else { count += 1; } } ``` If you have a situation in which your program has logic that is too verbose to express using a `match`, remember that `if let` is in your Rust toolbox as well. Summary ------- We’ve now covered how to use enums to create custom types that can be one of a set of enumerated values. We’ve shown how the standard library’s `Option<T>` type helps you use the type system to prevent errors. When enum values have data inside them, you can use `match` or `if let` to extract and use those values, depending on how many cases you need to handle. Your Rust programs can now express concepts in your domain using structs and enums. Creating custom types to use in your API ensures type safety: the compiler will make certain your functions get only values of the type each function expects. In order to provide a well-organized API to your users that is straightforward to use and only exposes exactly what your users will need, let’s now turn to Rust’s modules. rust Understanding Ownership Understanding Ownership ======================= Ownership is Rust’s most unique feature and has deep implications for the rest of the language. It enables Rust to make memory safety guarantees without needing a garbage collector, so it’s important to understand how ownership works. In this chapter, we’ll talk about ownership as well as several related features: borrowing, slices, and how Rust lays data out in memory. rust Separating Modules into Different Files Separating Modules into Different Files ======================================= So far, all the examples in this chapter defined multiple modules in one file. When modules get large, you might want to move their definitions to a separate file to make the code easier to navigate. For example, let’s start from the code in Listing 7-17 that had multiple restaurant modules. We’ll extract modules into files instead of having all the modules defined in the crate root file. In this case, the crate root file is *src/lib.rs*, but this procedure also works with binary crates whose crate root file is *src/main.rs*. First, we’ll extract the `front_of_house` module to its own file. Remove the code inside the curly brackets for the `front_of_house` module, leaving only the `mod front_of_house;` declaration, so that *src/lib.rs* contains the code shown in Listing 7-21. Note that this won’t compile until we create the *src/front\_of\_house.rs* file in Listing 7-22. Filename: src/lib.rs ``` mod front_of_house; pub use crate::front_of_house::hosting; pub fn eat_at_restaurant() { hosting::add_to_waitlist(); } ``` Listing 7-21: Declaring the `front_of_house` module whose body will be in *src/front\_of\_house.rs* Next, place the code that was in the curly brackets into a new file named *src/front\_of\_house.rs*, as shown in Listing 7-22. The compiler knows to look in this file because it came across the module declaration in the crate root with the name `front_of_house`. Filename: src/front\_of\_house.rs ``` pub mod hosting { pub fn add_to_waitlist() {} } ``` Listing 7-22: Definitions inside the `front_of_house` module in *src/front\_of\_house.rs* Note that you only need to load a file using a `mod` declaration *once* in your module tree. Once the compiler knows the file is part of the project (and knows where in the module tree the code resides because of where you’ve put the `mod` statement), other files in your project should refer to the loaded file’s code using a path to where it was declared, as covered in the [“Paths for Referring to an Item in the Module Tree”](ch07-03-paths-for-referring-to-an-item-in-the-module-tree) section. In other words, `mod` is *not* an “include” operation that you may have seen in other programming languages. Next, we’ll extract the `hosting` module to its own file. The process is a bit different because `hosting` is a child module of `front_of_house`, not of the root module. We’ll place the file for `hosting` in a new directory that will be named for its ancestors in the module tree, in this case *src/front\_of\_house/*. To start moving `hosting`, we change *src/front\_of\_house.rs* to contain only the declaration of the `hosting` module: Filename: src/front\_of\_house.rs ``` pub mod hosting; ``` Then we create a *src/front\_of\_house* directory and a file *hosting.rs* to contain the definitions made in the `hosting` module: Filename: src/front\_of\_house/hosting.rs ``` pub fn add_to_waitlist() {} ``` If we instead put *hosting.rs* in the *src* directory, the compiler would expect the *hosting.rs* code to be in a `hosting` module declared in the crate root, and not declared as a child of the `front_of_house` module. The compiler’s rules for which files to check for which modules’ code means the directories and files more closely match the module tree. > ### Alternate File Paths > > So far we’ve covered the most idiomatic file paths the Rust compiler uses, but Rust also supports an older style of file path. For a module named `front_of_house` declared in the crate root, the compiler will look for the module’s code in: > > * *src/front\_of\_house.rs* (what we covered) > * *src/front\_of\_house/mod.rs* (older style, still supported path) > > For a module named `hosting` that is a submodule of `front_of_house`, the compiler will look for the module’s code in: > > * *src/front\_of\_house/hosting.rs* (what we covered) > * *src/front\_of\_house/hosting/mod.rs* (older style, still supported path) > > If you use both styles for the same module, you’ll get a compiler error. Using a mix of both styles for different modules in the same project is allowed, but might be confusing for people navigating your project. > > The main downside to the style that uses files named *mod.rs* is that your project can end up with many files named *mod.rs*, which can get confusing when you have them open in your editor at the same time. > > We’ve moved each module’s code to a separate file, and the module tree remains the same. The function calls in `eat_at_restaurant` will work without any modification, even though the definitions live in different files. This technique lets you move modules to new files as they grow in size. Note that the `pub use crate::front_of_house::hosting` statement in *src/lib.rs* also hasn’t changed, nor does `use` have any impact on what files are compiled as part of the crate. The `mod` keyword declares modules, and Rust looks in a file with the same name as the module for the code that goes into that module. Summary ------- Rust lets you split a package into multiple crates and a crate into modules so you can refer to items defined in one module from another module. You can do this by specifying absolute or relative paths. These paths can be brought into scope with a `use` statement so you can use a shorter path for multiple uses of the item in that scope. Module code is private by default, but you can make definitions public by adding the `pub` keyword. In the next chapter, we’ll look at some collection data structures in the standard library that you can use in your neatly organized code. rust How to Write Tests How to Write Tests ================== Tests are Rust functions that verify that the non-test code is functioning in the expected manner. The bodies of test functions typically perform these three actions: 1. Set up any needed data or state. 2. Run the code you want to test. 3. Assert the results are what you expect. Let’s look at the features Rust provides specifically for writing tests that take these actions, which include the `test` attribute, a few macros, and the `should_panic` attribute. ### The Anatomy of a Test Function At its simplest, a test in Rust is a function that’s annotated with the `test` attribute. Attributes are metadata about pieces of Rust code; one example is the `derive` attribute we used with structs in Chapter 5. To change a function into a test function, add `#[test]` on the line before `fn`. When you run your tests with the `cargo test` command, Rust builds a test runner binary that runs the annotated functions and reports on whether each test function passes or fails. Whenever we make a new library project with Cargo, a test module with a test function in it is automatically generated for us. This module gives you a template for writing your tests so you don’t have to look up the exact structure and syntax every time you start a new project. You can add as many additional test functions and as many test modules as you want! We’ll explore some aspects of how tests work by experimenting with the template test before we actually test any code. Then we’ll write some real-world tests that call some code that we’ve written and assert that its behavior is correct. Let’s create a new library project called `adder` that will add two numbers: ``` $ cargo new adder --lib Created library `adder` project $ cd adder ``` The contents of the *src/lib.rs* file in your `adder` library should look like Listing 11-1. Filename: src/lib.rs ``` #[cfg(test)] mod tests { #[test] fn it_works() { let result = 2 + 2; assert_eq!(result, 4); } } ``` Listing 11-1: The test module and function generated automatically by `cargo new` For now, let’s ignore the top two lines and focus on the function. Note the `#[test]` annotation: this attribute indicates this is a test function, so the test runner knows to treat this function as a test. We might also have non-test functions in the `tests` module to help set up common scenarios or perform common operations, so we always need to indicate which functions are tests. The example function body uses the `assert_eq!` macro to assert that `result`, which contains the result of adding 2 and 2, equals 4. This assertion serves as an example of the format for a typical test. Let’s run it to see that this test passes. The `cargo test` command runs all tests in our project, as shown in Listing 11-2. ``` $ cargo test Compiling adder v0.1.0 (file:///projects/adder) Finished test [unoptimized + debuginfo] target(s) in 0.57s Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4) running 1 test test tests::it_works ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests adder running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` Listing 11-2: The output from running the automatically generated test Cargo compiled and ran the test. We see the line `running 1 test`. The next line shows the name of the generated test function, called `it_works`, and that the result of running that test is `ok`. The overall summary `test result: ok.` means that all the tests passed, and the portion that reads `1 passed; 0 failed` totals the number of tests that passed or failed. It’s possible to mark a test as ignored so it doesn’t run in a particular instance; we’ll cover that in the [“Ignoring Some Tests Unless Specifically Requested”](ch11-02-running-tests#ignoring-some-tests-unless-specifically-requested) section later in this chapter. Because we haven’t done that here, the summary shows `0 ignored`. We can also pass an argument to the `cargo test` command to run only tests whose name matches a string; this is called *filtering* and we’ll cover that in the [“Running a Subset of Tests by Name”](ch11-02-running-tests#running-a-subset-of-tests-by-name) section. We also haven’t filtered the tests being run, so the end of the summary shows `0 filtered out`. The `0 measured` statistic is for benchmark tests that measure performance. Benchmark tests are, as of this writing, only available in nightly Rust. See [the documentation about benchmark tests](https://doc.rust-lang.org/unstable-book/library-features/test.html) to learn more. The next part of the test output starting at `Doc-tests adder` is for the results of any documentation tests. We don’t have any documentation tests yet, but Rust can compile any code examples that appear in our API documentation. This feature helps keep your docs and your code in sync! We’ll discuss how to write documentation tests in the [“Documentation Comments as Tests”](ch14-02-publishing-to-crates-io#documentation-comments-as-tests) section of Chapter 14. For now, we’ll ignore the `Doc-tests` output. Let’s start to customize the test to our own needs. First change the name of the `it_works` function to a different name, such as `exploration`, like so: Filename: src/lib.rs ``` #[cfg(test)] mod tests { #[test] fn exploration() { assert_eq!(2 + 2, 4); } } ``` Then run `cargo test` again. The output now shows `exploration` instead of `it_works`: ``` $ cargo test Compiling adder v0.1.0 (file:///projects/adder) Finished test [unoptimized + debuginfo] target(s) in 0.59s Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4) running 1 test test tests::exploration ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests adder running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` Now we’ll add another test, but this time we’ll make a test that fails! Tests fail when something in the test function panics. Each test is run in a new thread, and when the main thread sees that a test thread has died, the test is marked as failed. In Chapter 9, we talked about how the simplest way to panic is to call the `panic!` macro. Enter the new test as a function named `another`, so your *src/lib.rs* file looks like Listing 11-3. Filename: src/lib.rs ``` #[cfg(test)] mod tests { #[test] fn exploration() { assert_eq!(2 + 2, 4); } #[test] fn another() { panic!("Make this test fail"); } } ``` Listing 11-3: Adding a second test that will fail because we call the `panic!` macro Run the tests again using `cargo test`. The output should look like Listing 11-4, which shows that our `exploration` test passed and `another` failed. ``` $ cargo test Compiling adder v0.1.0 (file:///projects/adder) Finished test [unoptimized + debuginfo] target(s) in 0.72s Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4) running 2 tests test tests::another ... FAILED test tests::exploration ... ok failures: ---- tests::another stdout ---- thread 'main' panicked at 'Make this test fail', src/lib.rs:10:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: tests::another test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--lib' ``` Listing 11-4: Test results when one test passes and one test fails Instead of `ok`, the line `test tests::another` shows `FAILED`. Two new sections appear between the individual results and the summary: the first displays the detailed reason for each test failure. In this case, we get the details that `another` failed because it `panicked at 'Make this test fail'` on line 10 in the *src/lib.rs* file. The next section lists just the names of all the failing tests, which is useful when there are lots of tests and lots of detailed failing test output. We can use the name of a failing test to run just that test to more easily debug it; we’ll talk more about ways to run tests in the [“Controlling How Tests Are Run”](ch11-02-running-tests#controlling-how-tests-are-run) section. The summary line displays at the end: overall, our test result is `FAILED`. We had one test pass and one test fail. Now that you’ve seen what the test results look like in different scenarios, let’s look at some macros other than `panic!` that are useful in tests. ### Checking Results with the `assert!` Macro The `assert!` macro, provided by the standard library, is useful when you want to ensure that some condition in a test evaluates to `true`. We give the `assert!` macro an argument that evaluates to a Boolean. If the value is `true`, nothing happens and the test passes. If the value is `false`, the `assert!` macro calls `panic!` to cause the test to fail. Using the `assert!` macro helps us check that our code is functioning in the way we intend. In Chapter 5, Listing 5-15, we used a `Rectangle` struct and a `can_hold` method, which are repeated here in Listing 11-5. Let’s put this code in the *src/lib.rs* file, then write some tests for it using the `assert!` macro. Filename: src/lib.rs ``` #[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } } ``` Listing 11-5: Using the `Rectangle` struct and its `can_hold` method from Chapter 5 The `can_hold` method returns a Boolean, which means it’s a perfect use case for the `assert!` macro. In Listing 11-6, we write a test that exercises the `can_hold` method by creating a `Rectangle` instance that has a width of 8 and a height of 7 and asserting that it can hold another `Rectangle` instance that has a width of 5 and a height of 1. Filename: src/lib.rs ``` #[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } } #[cfg(test)] mod tests { use super::*; #[test] fn larger_can_hold_smaller() { let larger = Rectangle { width: 8, height: 7, }; let smaller = Rectangle { width: 5, height: 1, }; assert!(larger.can_hold(&smaller)); } } ``` Listing 11-6: A test for `can_hold` that checks whether a larger rectangle can indeed hold a smaller rectangle Note that we’ve added a new line inside the `tests` module: `use super::*;`. The `tests` module is a regular module that follows the usual visibility rules we covered in Chapter 7 in the [“Paths for Referring to an Item in the Module Tree”](ch07-03-paths-for-referring-to-an-item-in-the-module-tree) section. Because the `tests` module is an inner module, we need to bring the code under test in the outer module into the scope of the inner module. We use a glob here so anything we define in the outer module is available to this `tests` module. We’ve named our test `larger_can_hold_smaller`, and we’ve created the two `Rectangle` instances that we need. Then we called the `assert!` macro and passed it the result of calling `larger.can_hold(&smaller)`. This expression is supposed to return `true`, so our test should pass. Let’s find out! ``` $ cargo test Compiling rectangle v0.1.0 (file:///projects/rectangle) Finished test [unoptimized + debuginfo] target(s) in 0.66s Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e) running 1 test test tests::larger_can_hold_smaller ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests rectangle running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` It does pass! Let’s add another test, this time asserting that a smaller rectangle cannot hold a larger rectangle: Filename: src/lib.rs ``` #[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } } #[cfg(test)] mod tests { use super::*; #[test] fn larger_can_hold_smaller() { // --snip-- let larger = Rectangle { width: 8, height: 7, }; let smaller = Rectangle { width: 5, height: 1, }; assert!(larger.can_hold(&smaller)); } #[test] fn smaller_cannot_hold_larger() { let larger = Rectangle { width: 8, height: 7, }; let smaller = Rectangle { width: 5, height: 1, }; assert!(!smaller.can_hold(&larger)); } } ``` Because the correct result of the `can_hold` function in this case is `false`, we need to negate that result before we pass it to the `assert!` macro. As a result, our test will pass if `can_hold` returns `false`: ``` $ cargo test Compiling rectangle v0.1.0 (file:///projects/rectangle) Finished test [unoptimized + debuginfo] target(s) in 0.66s Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e) running 2 tests test tests::larger_can_hold_smaller ... ok test tests::smaller_cannot_hold_larger ... ok test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests rectangle running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` Two tests that pass! Now let’s see what happens to our test results when we introduce a bug in our code. We’ll change the implementation of the `can_hold` method by replacing the greater-than sign with a less-than sign when it compares the widths: ``` #[derive(Debug)] struct Rectangle { width: u32, height: u32, } // --snip-- impl Rectangle { fn can_hold(&self, other: &Rectangle) -> bool { self.width < other.width && self.height > other.height } } #[cfg(test)] mod tests { use super::*; #[test] fn larger_can_hold_smaller() { let larger = Rectangle { width: 8, height: 7, }; let smaller = Rectangle { width: 5, height: 1, }; assert!(larger.can_hold(&smaller)); } #[test] fn smaller_cannot_hold_larger() { let larger = Rectangle { width: 8, height: 7, }; let smaller = Rectangle { width: 5, height: 1, }; assert!(!smaller.can_hold(&larger)); } } ``` Running the tests now produces the following: ``` $ cargo test Compiling rectangle v0.1.0 (file:///projects/rectangle) Finished test [unoptimized + debuginfo] target(s) in 0.66s Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e) running 2 tests test tests::larger_can_hold_smaller ... FAILED test tests::smaller_cannot_hold_larger ... ok failures: ---- tests::larger_can_hold_smaller stdout ---- thread 'main' panicked at 'assertion failed: larger.can_hold(&smaller)', src/lib.rs:28:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: tests::larger_can_hold_smaller test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--lib' ``` Our tests caught the bug! Because `larger.width` is 8 and `smaller.width` is 5, the comparison of the widths in `can_hold` now returns `false`: 8 is not less than 5. ### Testing Equality with the `assert_eq!` and `assert_ne!` Macros A common way to verify functionality is to test for equality between the result of the code under test and the value you expect the code to return. You could do this using the `assert!` macro and passing it an expression using the `==` operator. However, this is such a common test that the standard library provides a pair of macros—`assert_eq!` and `assert_ne!`—to perform this test more conveniently. These macros compare two arguments for equality or inequality, respectively. They’ll also print the two values if the assertion fails, which makes it easier to see *why* the test failed; conversely, the `assert!` macro only indicates that it got a `false` value for the `==` expression, without printing the values that led to the `false` value. In Listing 11-7, we write a function named `add_two` that adds `2` to its parameter, then we test this function using the `assert_eq!` macro. Filename: src/lib.rs ``` pub fn add_two(a: i32) -> i32 { a + 2 } #[cfg(test)] mod tests { use super::*; #[test] fn it_adds_two() { assert_eq!(4, add_two(2)); } } ``` Listing 11-7: Testing the function `add_two` using the `assert_eq!` macro Let’s check that it passes! ``` $ cargo test Compiling adder v0.1.0 (file:///projects/adder) Finished test [unoptimized + debuginfo] target(s) in 0.58s Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4) running 1 test test tests::it_adds_two ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests adder running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` We pass `4` as the argument to `assert_eq!`, which is equal to the result of calling `add_two(2)`. The line for this test is `test tests::it_adds_two ... ok`, and the `ok` text indicates that our test passed! Let’s introduce a bug into our code to see what `assert_eq!` looks like when it fails. Change the implementation of the `add_two` function to instead add `3`: ``` pub fn add_two(a: i32) -> i32 { a + 3 } #[cfg(test)] mod tests { use super::*; #[test] fn it_adds_two() { assert_eq!(4, add_two(2)); } } ``` Run the tests again: ``` $ cargo test Compiling adder v0.1.0 (file:///projects/adder) Finished test [unoptimized + debuginfo] target(s) in 0.61s Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4) running 1 test test tests::it_adds_two ... FAILED failures: ---- tests::it_adds_two stdout ---- thread 'main' panicked at 'assertion failed: `(left == right)` left: `4`, right: `5`', src/lib.rs:11:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: tests::it_adds_two test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--lib' ``` Our test caught the bug! The `it_adds_two` test failed, and the message tells us that the assertion that fails was `assertion failed: `(left == right)`` and what the `left` and `right` values are. This message helps us start debugging: the `left` argument was `4` but the `right` argument, where we had `add_two(2)`, was `5`. You can imagine that this would be especially helpful when we have a lot of tests going on. Note that in some languages and test frameworks, the parameters to equality assertion functions are called `expected` and `actual`, and the order in which we specify the arguments matters. However, in Rust, they’re called `left` and `right`, and the order in which we specify the value we expect and the value the code produces doesn’t matter. We could write the assertion in this test as `assert_eq!(add_two(2), 4)`, which would result in the same failure message that displays `assertion failed: `(left == right)``. The `assert_ne!` macro will pass if the two values we give it are not equal and fail if they’re equal. This macro is most useful for cases when we’re not sure what a value *will* be, but we know what the value definitely *shouldn’t* be. For example, if we’re testing a function that is guaranteed to change its input in some way, but the way in which the input is changed depends on the day of the week that we run our tests, the best thing to assert might be that the output of the function is not equal to the input. Under the surface, the `assert_eq!` and `assert_ne!` macros use the operators `==` and `!=`, respectively. When the assertions fail, these macros print their arguments using debug formatting, which means the values being compared must implement the `PartialEq` and `Debug` traits. All primitive types and most of the standard library types implement these traits. For structs and enums that you define yourself, you’ll need to implement `PartialEq` to assert equality of those types. You’ll also need to implement `Debug` to print the values when the assertion fails. Because both traits are derivable traits, as mentioned in Listing 5-12 in Chapter 5, this is usually as straightforward as adding the `#[derive(PartialEq, Debug)]` annotation to your struct or enum definition. See Appendix C, [“Derivable Traits,”](appendix-03-derivable-traits) for more details about these and other derivable traits. ### Adding Custom Failure Messages You can also add a custom message to be printed with the failure message as optional arguments to the `assert!`, `assert_eq!`, and `assert_ne!` macros. Any arguments specified after the required arguments are passed along to the `format!` macro (discussed in Chapter 8 in the [“Concatenation with the `+` Operator or the `format!` Macro”](ch08-02-strings#concatenation-with-the--operator-or-the-format-macro) section), so you can pass a format string that contains `{}` placeholders and values to go in those placeholders. Custom messages are useful for documenting what an assertion means; when a test fails, you’ll have a better idea of what the problem is with the code. For example, let’s say we have a function that greets people by name and we want to test that the name we pass into the function appears in the output: Filename: src/lib.rs ``` pub fn greeting(name: &str) -> String { format!("Hello {}!", name) } #[cfg(test)] mod tests { use super::*; #[test] fn greeting_contains_name() { let result = greeting("Carol"); assert!(result.contains("Carol")); } } ``` The requirements for this program haven’t been agreed upon yet, and we’re pretty sure the `Hello` text at the beginning of the greeting will change. We decided we don’t want to have to update the test when the requirements change, so instead of checking for exact equality to the value returned from the `greeting` function, we’ll just assert that the output contains the text of the input parameter. Now let’s introduce a bug into this code by changing `greeting` to exclude `name` to see what the default test failure looks like: ``` pub fn greeting(name: &str) -> String { String::from("Hello!") } #[cfg(test)] mod tests { use super::*; #[test] fn greeting_contains_name() { let result = greeting("Carol"); assert!(result.contains("Carol")); } } ``` Running this test produces the following: ``` $ cargo test Compiling greeter v0.1.0 (file:///projects/greeter) Finished test [unoptimized + debuginfo] target(s) in 0.91s Running unittests src/lib.rs (target/debug/deps/greeter-170b942eb5bf5e3a) running 1 test test tests::greeting_contains_name ... FAILED failures: ---- tests::greeting_contains_name stdout ---- thread 'main' panicked at 'assertion failed: result.contains(\"Carol\")', src/lib.rs:12:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: tests::greeting_contains_name test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--lib' ``` This result just indicates that the assertion failed and which line the assertion is on. A more useful failure message would print the value from the `greeting` function. Let’s add a custom failure message composed of a format string with a placeholder filled in with the actual value we got from the `greeting` function: ``` pub fn greeting(name: &str) -> String { String::from("Hello!") } #[cfg(test)] mod tests { use super::*; #[test] fn greeting_contains_name() { let result = greeting("Carol"); assert!( result.contains("Carol"), "Greeting did not contain name, value was `{}`", result ); } } ``` Now when we run the test, we’ll get a more informative error message: ``` $ cargo test Compiling greeter v0.1.0 (file:///projects/greeter) Finished test [unoptimized + debuginfo] target(s) in 0.93s Running unittests src/lib.rs (target/debug/deps/greeter-170b942eb5bf5e3a) running 1 test test tests::greeting_contains_name ... FAILED failures: ---- tests::greeting_contains_name stdout ---- thread 'main' panicked at 'Greeting did not contain name, value was `Hello!`', src/lib.rs:12:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: tests::greeting_contains_name test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--lib' ``` We can see the value we actually got in the test output, which would help us debug what happened instead of what we were expecting to happen. ### Checking for Panics with `should_panic` In addition to checking return values, it’s important to check that our code handles error conditions as we expect. For example, consider the `Guess` type that we created in Chapter 9, Listing 9-13. Other code that uses `Guess` depends on the guarantee that `Guess` instances will contain only values between 1 and 100. We can write a test that ensures that attempting to create a `Guess` instance with a value outside that range panics. We do this by adding the attribute `should_panic` to our test function. The test passes if the code inside the function panics; the test fails if the code inside the function doesn’t panic. Listing 11-8 shows a test that checks that the error conditions of `Guess::new` happen when we expect them to. Filename: src/lib.rs ``` pub struct Guess { value: i32, } impl Guess { pub fn new(value: i32) -> Guess { if value < 1 || value > 100 { panic!("Guess value must be between 1 and 100, got {}.", value); } Guess { value } } } #[cfg(test)] mod tests { use super::*; #[test] #[should_panic] fn greater_than_100() { Guess::new(200); } } ``` Listing 11-8: Testing that a condition will cause a `panic!` We place the `#[should_panic]` attribute after the `#[test]` attribute and before the test function it applies to. Let’s look at the result when this test passes: ``` $ cargo test Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished test [unoptimized + debuginfo] target(s) in 0.58s Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d) running 1 test test tests::greater_than_100 - should panic ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests guessing_game running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` Looks good! Now let’s introduce a bug in our code by removing the condition that the `new` function will panic if the value is greater than 100: ``` pub struct Guess { value: i32, } // --snip-- impl Guess { pub fn new(value: i32) -> Guess { if value < 1 { panic!("Guess value must be between 1 and 100, got {}.", value); } Guess { value } } } #[cfg(test)] mod tests { use super::*; #[test] #[should_panic] fn greater_than_100() { Guess::new(200); } } ``` When we run the test in Listing 11-8, it will fail: ``` $ cargo test Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished test [unoptimized + debuginfo] target(s) in 0.62s Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d) running 1 test test tests::greater_than_100 - should panic ... FAILED failures: ---- tests::greater_than_100 stdout ---- note: test did not panic as expected failures: tests::greater_than_100 test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--lib' ``` We don’t get a very helpful message in this case, but when we look at the test function, we see that it’s annotated with `#[should_panic]`. The failure we got means that the code in the test function did not cause a panic. Tests that use `should_panic` can be imprecise. A `should_panic` test would pass even if the test panics for a different reason from the one we were expecting. To make `should_panic` tests more precise, we can add an optional `expected` parameter to the `should_panic` attribute. The test harness will make sure that the failure message contains the provided text. For example, consider the modified code for `Guess` in Listing 11-9 where the `new` function panics with different messages depending on whether the value is too small or too large. Filename: src/lib.rs ``` pub struct Guess { value: i32, } // --snip-- impl Guess { pub fn new(value: i32) -> Guess { if value < 1 { panic!( "Guess value must be greater than or equal to 1, got {}.", value ); } else if value > 100 { panic!( "Guess value must be less than or equal to 100, got {}.", value ); } Guess { value } } } #[cfg(test)] mod tests { use super::*; #[test] #[should_panic(expected = "less than or equal to 100")] fn greater_than_100() { Guess::new(200); } } ``` Listing 11-9: Testing for a `panic!` with a panic message containing a specified substring This test will pass because the value we put in the `should_panic` attribute’s `expected` parameter is a substring of the message that the `Guess::new` function panics with. We could have specified the entire panic message that we expect, which in this case would be `Guess value must be less than or equal to 100, got 200.` What you choose to specify depends on how much of the panic message is unique or dynamic and how precise you want your test to be. In this case, a substring of the panic message is enough to ensure that the code in the test function executes the `else if value > 100` case. To see what happens when a `should_panic` test with an `expected` message fails, let’s again introduce a bug into our code by swapping the bodies of the `if value < 1` and the `else if value > 100` blocks: ``` pub struct Guess { value: i32, } impl Guess { pub fn new(value: i32) -> Guess { if value < 1 { panic!( "Guess value must be less than or equal to 100, got {}.", value ); } else if value > 100 { panic!( "Guess value must be greater than or equal to 1, got {}.", value ); } Guess { value } } } #[cfg(test)] mod tests { use super::*; #[test] #[should_panic(expected = "less than or equal to 100")] fn greater_than_100() { Guess::new(200); } } ``` This time when we run the `should_panic` test, it will fail: ``` $ cargo test Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished test [unoptimized + debuginfo] target(s) in 0.66s Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d) running 1 test test tests::greater_than_100 - should panic ... FAILED failures: ---- tests::greater_than_100 stdout ---- thread 'main' panicked at 'Guess value must be greater than or equal to 1, got 200.', src/lib.rs:13:13 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace note: panic did not contain expected string panic message: `"Guess value must be greater than or equal to 1, got 200."`, expected substring: `"less than or equal to 100"` failures: tests::greater_than_100 test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--lib' ``` The failure message indicates that this test did indeed panic as we expected, but the panic message did not include the expected string `'Guess value must be less than or equal to 100'`. The panic message that we did get in this case was `Guess value must be greater than or equal to 1, got 200.` Now we can start figuring out where our bug is! ### Using `Result<T, E>` in Tests Our tests so far all panic when they fail. We can also write tests that use `Result<T, E>`! Here’s the test from Listing 11-1, rewritten to use `Result<T, E>` and return an `Err` instead of panicking: ``` #[cfg(test)] mod tests { #[test] fn it_works() -> Result<(), String> { if 2 + 2 == 4 { Ok(()) } else { Err(String::from("two plus two does not equal four")) } } } ``` The `it_works` function now has the `Result<(), String>` return type. In the body of the function, rather than calling the `assert_eq!` macro, we return `Ok(())` when the test passes and an `Err` with a `String` inside when the test fails. Writing tests so they return a `Result<T, E>` enables you to use the question mark operator in the body of tests, which can be a convenient way to write tests that should fail if any operation within them returns an `Err` variant. You can’t use the `#[should_panic]` annotation on tests that use `Result<T, E>`. To assert that an operation returns an `Err` variant, *don’t* use the question mark operator on the `Result<T, E>` value. Instead, use `assert!(value.is_err())`. Now that you know several ways to write tests, let’s look at what is happening when we run our tests and explore the different options we can use with `cargo test`.
programming_docs
rust Getting Started Getting Started =============== Let’s start your Rust journey! There’s a lot to learn, but every journey starts somewhere. In this chapter, we’ll discuss: * Installing Rust on Linux, macOS, and Windows * Writing a program that prints `Hello, world!` * Using `cargo`, Rust’s package manager and build system rust An Example Program Using Structs An Example Program Using Structs ================================ To understand when we might want to use structs, let’s write a program that calculates the area of a rectangle. We’ll start by using single variables, and then refactor the program until we’re using structs instead. Let’s make a new binary project with Cargo called *rectangles* that will take the width and height of a rectangle specified in pixels and calculate the area of the rectangle. Listing 5-8 shows a short program with one way of doing exactly that in our project’s *src/main.rs*. Filename: src/main.rs ``` fn main() { let width1 = 30; let height1 = 50; println!( "The area of the rectangle is {} square pixels.", area(width1, height1) ); } fn area(width: u32, height: u32) -> u32 { width * height } ``` Listing 5-8: Calculating the area of a rectangle specified by separate width and height variables Now, run this program using `cargo run`: ``` $ cargo run Compiling rectangles v0.1.0 (file:///projects/rectangles) Finished dev [unoptimized + debuginfo] target(s) in 0.42s Running `target/debug/rectangles` The area of the rectangle is 1500 square pixels. ``` This code succeeds in figuring out the area of the rectangle by calling the `area` function with each dimension, but we can do more to make this code clear and readable. The issue with this code is evident in the signature of `area`: ``` fn main() { let width1 = 30; let height1 = 50; println!( "The area of the rectangle is {} square pixels.", area(width1, height1) ); } fn area(width: u32, height: u32) -> u32 { width * height } ``` The `area` function is supposed to calculate the area of one rectangle, but the function we wrote has two parameters, and it’s not clear anywhere in our program that the parameters are related. It would be more readable and more manageable to group width and height together. We’ve already discussed one way we might do that in [“The Tuple Type”](ch03-02-data-types#the-tuple-type) section of Chapter 3: by using tuples. ### Refactoring with Tuples Listing 5-9 shows another version of our program that uses tuples. Filename: src/main.rs ``` fn main() { let rect1 = (30, 50); println!( "The area of the rectangle is {} square pixels.", area(rect1) ); } fn area(dimensions: (u32, u32)) -> u32 { dimensions.0 * dimensions.1 } ``` Listing 5-9: Specifying the width and height of the rectangle with a tuple In one way, this program is better. Tuples let us add a bit of structure, and we’re now passing just one argument. But in another way, this version is less clear: tuples don’t name their elements, so we have to index into the parts of the tuple, making our calculation less obvious. Mixing up the width and height wouldn’t matter for the area calculation, but if we want to draw the rectangle on the screen, it would matter! We would have to keep in mind that `width` is the tuple index `0` and `height` is the tuple index `1`. This would be even harder for someone else to figure out and keep in mind if they were to use our code. Because we haven’t conveyed the meaning of our data in our code, it’s now easier to introduce errors. ### Refactoring with Structs: Adding More Meaning We use structs to add meaning by labeling the data. We can transform the tuple we’re using into a struct with a name for the whole as well as names for the parts, as shown in Listing 5-10. Filename: src/main.rs ``` struct Rectangle { width: u32, height: u32, } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; println!( "The area of the rectangle is {} square pixels.", area(&rect1) ); } fn area(rectangle: &Rectangle) -> u32 { rectangle.width * rectangle.height } ``` Listing 5-10: Defining a `Rectangle` struct Here we’ve defined a struct and named it `Rectangle`. Inside the curly brackets, we defined the fields as `width` and `height`, both of which have type `u32`. Then in `main`, we created a particular instance of `Rectangle` that has a width of 30 and a height of 50. Our `area` function is now defined with one parameter, which we’ve named `rectangle`, whose type is an immutable borrow of a struct `Rectangle` instance. As mentioned in Chapter 4, we want to borrow the struct rather than take ownership of it. This way, `main` retains its ownership and can continue using `rect1`, which is the reason we use the `&` in the function signature and where we call the function. The `area` function accesses the `width` and `height` fields of the `Rectangle` instance (note that accessing fields of a borrowed struct instance does not move the field values, which is why you often see borrows of structs). Our function signature for `area` now says exactly what we mean: calculate the area of `Rectangle`, using its `width` and `height` fields. This conveys that the width and height are related to each other, and it gives descriptive names to the values rather than using the tuple index values of `0` and `1`. This is a win for clarity. ### Adding Useful Functionality with Derived Traits It’d be useful to be able to print an instance of `Rectangle` while we’re debugging our program and see the values for all its fields. Listing 5-11 tries using the [`println!` macro](../std/macro.println) as we have used in previous chapters. This won’t work, however. Filename: src/main.rs ``` struct Rectangle { width: u32, height: u32, } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; println!("rect1 is {}", rect1); } ``` Listing 5-11: Attempting to print a `Rectangle` instance When we compile this code, we get an error with this core message: ``` error[E0277]: `Rectangle` doesn't implement `std::fmt::Display` ``` The `println!` macro can do many kinds of formatting, and by default, the curly brackets tell `println!` to use formatting known as `Display`: output intended for direct end user consumption. The primitive types we’ve seen so far implement `Display` by default, because there’s only one way you’d want to show a `1` or any other primitive type to a user. But with structs, the way `println!` should format the output is less clear because there are more display possibilities: Do you want commas or not? Do you want to print the curly brackets? Should all the fields be shown? Due to this ambiguity, Rust doesn’t try to guess what we want, and structs don’t have a provided implementation of `Display` to use with `println!` and the `{}` placeholder. If we continue reading the errors, we’ll find this helpful note: ``` = help: the trait `std::fmt::Display` is not implemented for `Rectangle` = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead ``` Let’s try it! The `println!` macro call will now look like `println!("rect1 is {:?}", rect1);`. Putting the specifier `:?` inside the curly brackets tells `println!` we want to use an output format called `Debug`. The `Debug` trait enables us to print our struct in a way that is useful for developers so we can see its value while we’re debugging our code. Compile the code with this change. Drat! We still get an error: ``` error[E0277]: `Rectangle` doesn't implement `Debug` ``` But again, the compiler gives us a helpful note: ``` = help: the trait `Debug` is not implemented for `Rectangle` = note: add `#[derive(Debug)]` to `Rectangle` or manually `impl Debug for Rectangle` ``` Rust *does* include functionality to print out debugging information, but we have to explicitly opt in to make that functionality available for our struct. To do that, we add the outer attribute `#[derive(Debug)]` just before the struct definition, as shown in Listing 5-12. Filename: src/main.rs ``` #[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; println!("rect1 is {:?}", rect1); } ``` Listing 5-12: Adding the attribute to derive the `Debug` trait and printing the `Rectangle` instance using debug formatting Now when we run the program, we won’t get any errors, and we’ll see the following output: ``` $ cargo run Compiling rectangles v0.1.0 (file:///projects/rectangles) Finished dev [unoptimized + debuginfo] target(s) in 0.48s Running `target/debug/rectangles` rect1 is Rectangle { width: 30, height: 50 } ``` Nice! It’s not the prettiest output, but it shows the values of all the fields for this instance, which would definitely help during debugging. When we have larger structs, it’s useful to have output that’s a bit easier to read; in those cases, we can use `{:#?}` instead of `{:?}` in the `println!` string. In this example, using the `{:#?}` style will output: ``` $ cargo run Compiling rectangles v0.1.0 (file:///projects/rectangles) Finished dev [unoptimized + debuginfo] target(s) in 0.48s Running `target/debug/rectangles` rect1 is Rectangle { width: 30, height: 50, } ``` Another way to print out a value using the `Debug` format is to use the [`dbg!` macro](../std/macro.dbg), which takes ownership of an expression (as opposed to `println!` that takes a reference), prints the file and line number of where that `dbg!` macro call occurs in your code along with the resulting value of that expression, and returns ownership of the value. > Note: Calling the `dbg!` macro prints to the standard error console stream (`stderr`), as opposed to `println!` which prints to the standard output console stream (`stdout`). We’ll talk more about `stderr` and `stdout` in the “[“Writing Error Messages to Standard Error Instead of Standard Output” section in Chapter 12](ch12-06-writing-to-stderr-instead-of-stdout). > > Here’s an example where we’re interested in the value that gets assigned to the `width` field, as well as the value of the whole struct in `rect1`: ``` #[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let scale = 2; let rect1 = Rectangle { width: dbg!(30 * scale), height: 50, }; dbg!(&rect1); } ``` We can put `dbg!` around the expression `30 * scale` and, because `dbg!` returns ownership of the expression’s value, the `width` field will get the same value as if we didn’t have the `dbg!` call there. We don’t want `dbg!` to take ownership of `rect1`, so we use a reference to `rect1` in the next call. Here’s what the output of this example looks like: ``` $ cargo run Compiling rectangles v0.1.0 (file:///projects/rectangles) Finished dev [unoptimized + debuginfo] target(s) in 0.61s Running `target/debug/rectangles` [src/main.rs:10] 30 * scale = 60 [src/main.rs:14] &rect1 = Rectangle { width: 60, height: 50, } ``` We can see the first bit of output came from *src/main.rs* line 10, where we’re debugging the expression `30 * scale`, and its resulting value is 60 (the `Debug` formatting implemented for integers is to print only their value). The `dbg!` call on line 14 of *src/main.rs* outputs the value of `&rect1`, which is the `Rectangle` struct. This output uses the pretty `Debug` formatting of the `Rectangle` type. The `dbg!` macro can be really helpful when you’re trying to figure out what your code is doing! In addition to the `Debug` trait, Rust has provided a number of traits for us to use with the `derive` attribute that can add useful behavior to our custom types. Those traits and their behaviors are listed in [Appendix C](appendix-03-derivable-traits). We’ll cover how to implement these traits with custom behavior as well as how to create your own traits in Chapter 10. There are also many attributes other than `derive`; for more information, see [the “Attributes” section of the Rust Reference](../reference/attributes). Our `area` function is very specific: it only computes the area of rectangles. It would be helpful to tie this behavior more closely to our `Rectangle` struct, because it won’t work with any other type. Let’s look at how we can continue to refactor this code by turning the `area` function into an `area` *method* defined on our `Rectangle` type. rust Common Programming Concepts Common Programming Concepts =========================== This chapter covers concepts that appear in almost every programming language and how they work in Rust. Many programming languages have much in common at their core. None of the concepts presented in this chapter are unique to Rust, but we’ll discuss them in the context of Rust and explain the conventions around using these concepts. Specifically, you’ll learn about variables, basic types, functions, comments, and control flow. These foundations will be in every Rust program, and learning them early will give you a strong core to start from. > #### Keywords > > The Rust language has a set of *keywords* that are reserved for use by the language only, much as in other languages. Keep in mind that you cannot use these words as names of variables or functions. Most of the keywords have special meanings, and you’ll be using them to do various tasks in your Rust programs; a few have no current functionality associated with them but have been reserved for functionality that might be added to Rust in the future. You can find a list of the keywords in [Appendix A](appendix-01-keywords). > > rust Refactoring to Improve Modularity and Error Handling Refactoring to Improve Modularity and Error Handling ==================================================== To improve our program, we’ll fix four problems that have to do with the program’s structure and how it’s handling potential errors. First, our `main` function now performs two tasks: it parses arguments and reads files. As our program grows, the number of separate tasks the `main` function handles will increase. As a function gains responsibilities, it becomes more difficult to reason about, harder to test, and harder to change without breaking one of its parts. It’s best to separate functionality so each function is responsible for one task. This issue also ties into the second problem: although `query` and `file_path` are configuration variables to our program, variables like `contents` are used to perform the program’s logic. The longer `main` becomes, the more variables we’ll need to bring into scope; the more variables we have in scope, the harder it will be to keep track of the purpose of each. It’s best to group the configuration variables into one structure to make their purpose clear. The third problem is that we’ve used `expect` to print an error message when reading the file fails, but the error message just prints `Should have been able to read the file`. Reading a file can fail in a number of ways: for example, the file could be missing, or we might not have permission to open it. Right now, regardless of the situation, we’d print the same error message for everything, which wouldn’t give the user any information! Fourth, we use `expect` repeatedly to handle different errors, and if the user runs our program without specifying enough arguments, they’ll get an `index out of bounds` error from Rust that doesn’t clearly explain the problem. It would be best if all the error-handling code were in one place so future maintainers had only one place to consult the code if the error-handling logic needed to change. Having all the error-handling code in one place will also ensure that we’re printing messages that will be meaningful to our end users. Let’s address these four problems by refactoring our project. ### Separation of Concerns for Binary Projects The organizational problem of allocating responsibility for multiple tasks to the `main` function is common to many binary projects. As a result, the Rust community has developed guidelines for splitting the separate concerns of a binary program when `main` starts getting large. This process has the following steps: * Split your program into a *main.rs* and a *lib.rs* and move your program’s logic to *lib.rs*. * As long as your command line parsing logic is small, it can remain in *main.rs*. * When the command line parsing logic starts getting complicated, extract it from *main.rs* and move it to *lib.rs*. The responsibilities that remain in the `main` function after this process should be limited to the following: * Calling the command line parsing logic with the argument values * Setting up any other configuration * Calling a `run` function in *lib.rs* * Handling the error if `run` returns an error This pattern is about separating concerns: *main.rs* handles running the program, and *lib.rs* handles all the logic of the task at hand. Because you can’t test the `main` function directly, this structure lets you test all of your program’s logic by moving it into functions in *lib.rs*. The code that remains in *main.rs* will be small enough to verify its correctness by reading it. Let’s rework our program by following this process. #### Extracting the Argument Parser We’ll extract the functionality for parsing arguments into a function that `main` will call to prepare for moving the command line parsing logic to *src/lib.rs*. Listing 12-5 shows the new start of `main` that calls a new function `parse_config`, which we’ll define in *src/main.rs* for the moment. Filename: src/main.rs ``` use std::env; use std::fs; fn main() { let args: Vec<String> = env::args().collect(); let (query, file_path) = parse_config(&args); // --snip-- println!("Searching for {}", query); println!("In file {}", file_path); let contents = fs::read_to_string(file_path) .expect("Should have been able to read the file"); println!("With text:\n{contents}"); } fn parse_config(args: &[String]) -> (&str, &str) { let query = &args[1]; let file_path = &args[2]; (query, file_path) } ``` Listing 12-5: Extracting a `parse_config` function from `main` We’re still collecting the command line arguments into a vector, but instead of assigning the argument value at index 1 to the variable `query` and the argument value at index 2 to the variable `file_path` within the `main` function, we pass the whole vector to the `parse_config` function. The `parse_config` function then holds the logic that determines which argument goes in which variable and passes the values back to `main`. We still create the `query` and `file_path` variables in `main`, but `main` no longer has the responsibility of determining how the command line arguments and variables correspond. This rework may seem like overkill for our small program, but we’re refactoring in small, incremental steps. After making this change, run the program again to verify that the argument parsing still works. It’s good to check your progress often, to help identify the cause of problems when they occur. #### Grouping Configuration Values We can take another small step to improve the `parse_config` function further. At the moment, we’re returning a tuple, but then we immediately break that tuple into individual parts again. This is a sign that perhaps we don’t have the right abstraction yet. Another indicator that shows there’s room for improvement is the `config` part of `parse_config`, which implies that the two values we return are related and are both part of one configuration value. We’re not currently conveying this meaning in the structure of the data other than by grouping the two values into a tuple; we’ll instead put the two values into one struct and give each of the struct fields a meaningful name. Doing so will make it easier for future maintainers of this code to understand how the different values relate to each other and what their purpose is. Listing 12-6 shows the improvements to the `parse_config` function. Filename: src/main.rs ``` use std::env; use std::fs; fn main() { let args: Vec<String> = env::args().collect(); let config = parse_config(&args); println!("Searching for {}", config.query); println!("In file {}", config.file_path); let contents = fs::read_to_string(config.file_path) .expect("Should have been able to read the file"); // --snip-- println!("With text:\n{contents}"); } struct Config { query: String, file_path: String, } fn parse_config(args: &[String]) -> Config { let query = args[1].clone(); let file_path = args[2].clone(); Config { query, file_path } } ``` Listing 12-6: Refactoring `parse_config` to return an instance of a `Config` struct We’ve added a struct named `Config` defined to have fields named `query` and `file_path`. The signature of `parse_config` now indicates that it returns a `Config` value. In the body of `parse_config`, where we used to return string slices that reference `String` values in `args`, we now define `Config` to contain owned `String` values. The `args` variable in `main` is the owner of the argument values and is only letting the `parse_config` function borrow them, which means we’d violate Rust’s borrowing rules if `Config` tried to take ownership of the values in `args`. There are a number of ways we could manage the `String` data; the easiest, though somewhat inefficient, route is to call the `clone` method on the values. This will make a full copy of the data for the `Config` instance to own, which takes more time and memory than storing a reference to the string data. However, cloning the data also makes our code very straightforward because we don’t have to manage the lifetimes of the references; in this circumstance, giving up a little performance to gain simplicity is a worthwhile trade-off. > ### The Trade-Offs of Using `clone` > > There’s a tendency among many Rustaceans to avoid using `clone` to fix ownership problems because of its runtime cost. In [Chapter 13](ch13-00-functional-features), you’ll learn how to use more efficient methods in this type of situation. But for now, it’s okay to copy a few strings to continue making progress because you’ll make these copies only once and your file path and query string are very small. It’s better to have a working program that’s a bit inefficient than to try to hyperoptimize code on your first pass. As you become more experienced with Rust, it’ll be easier to start with the most efficient solution, but for now, it’s perfectly acceptable to call `clone`. > > We’ve updated `main` so it places the instance of `Config` returned by `parse_config` into a variable named `config`, and we updated the code that previously used the separate `query` and `file_path` variables so it now uses the fields on the `Config` struct instead. Now our code more clearly conveys that `query` and `file_path` are related and that their purpose is to configure how the program will work. Any code that uses these values knows to find them in the `config` instance in the fields named for their purpose. #### Creating a Constructor for `Config` So far, we’ve extracted the logic responsible for parsing the command line arguments from `main` and placed it in the `parse_config` function. Doing so helped us to see that the `query` and `file_path` values were related and that relationship should be conveyed in our code. We then added a `Config` struct to name the related purpose of `query` and `file_path` and to be able to return the values’ names as struct field names from the `parse_config` function. So now that the purpose of the `parse_config` function is to create a `Config` instance, we can change `parse_config` from a plain function to a function named `new` that is associated with the `Config` struct. Making this change will make the code more idiomatic. We can create instances of types in the standard library, such as `String`, by calling `String::new`. Similarly, by changing `parse_config` into a `new` function associated with `Config`, we’ll be able to create instances of `Config` by calling `Config::new`. Listing 12-7 shows the changes we need to make. Filename: src/main.rs ``` use std::env; use std::fs; fn main() { let args: Vec<String> = env::args().collect(); let config = Config::new(&args); println!("Searching for {}", config.query); println!("In file {}", config.file_path); let contents = fs::read_to_string(config.file_path) .expect("Should have been able to read the file"); println!("With text:\n{contents}"); // --snip-- } // --snip-- struct Config { query: String, file_path: String, } impl Config { fn new(args: &[String]) -> Config { let query = args[1].clone(); let file_path = args[2].clone(); Config { query, file_path } } } ``` Listing 12-7: Changing `parse_config` into `Config::new` We’ve updated `main` where we were calling `parse_config` to instead call `Config::new`. We’ve changed the name of `parse_config` to `new` and moved it within an `impl` block, which associates the `new` function with `Config`. Try compiling this code again to make sure it works. ### Fixing the Error Handling Now we’ll work on fixing our error handling. Recall that attempting to access the values in the `args` vector at index 1 or index 2 will cause the program to panic if the vector contains fewer than three items. Try running the program without any arguments; it will look like this: ``` $ cargo run Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished dev [unoptimized + debuginfo] target(s) in 0.0s Running `target/debug/minigrep` thread 'main' panicked at 'index out of bounds: the len is 1 but the index is 1', src/main.rs:27:21 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` The line `index out of bounds: the len is 1 but the index is 1` is an error message intended for programmers. It won’t help our end users understand what they should do instead. Let’s fix that now. #### Improving the Error Message In Listing 12-8, we add a check in the `new` function that will verify that the slice is long enough before accessing index 1 and 2. If the slice isn’t long enough, the program panics and displays a better error message. Filename: src/main.rs ``` use std::env; use std::fs; fn main() { let args: Vec<String> = env::args().collect(); let config = Config::new(&args); println!("Searching for {}", config.query); println!("In file {}", config.file_path); let contents = fs::read_to_string(config.file_path) .expect("Should have been able to read the file"); println!("With text:\n{contents}"); } struct Config { query: String, file_path: String, } impl Config { // --snip-- fn new(args: &[String]) -> Config { if args.len() < 3 { panic!("not enough arguments"); } // --snip-- let query = args[1].clone(); let file_path = args[2].clone(); Config { query, file_path } } } ``` Listing 12-8: Adding a check for the number of arguments This code is similar to [the `Guess::new` function we wrote in Listing 9-13](ch09-03-to-panic-or-not-to-panic#creating-custom-types-for-validation), where we called `panic!` when the `value` argument was out of the range of valid values. Instead of checking for a range of values here, we’re checking that the length of `args` is at least 3 and the rest of the function can operate under the assumption that this condition has been met. If `args` has fewer than three items, this condition will be true, and we call the `panic!` macro to end the program immediately. With these extra few lines of code in `new`, let’s run the program without any arguments again to see what the error looks like now: ``` $ cargo run Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished dev [unoptimized + debuginfo] target(s) in 0.0s Running `target/debug/minigrep` thread 'main' panicked at 'not enough arguments', src/main.rs:26:13 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` This output is better: we now have a reasonable error message. However, we also have extraneous information we don’t want to give to our users. Perhaps using the technique we used in Listing 9-13 isn’t the best to use here: a call to `panic!` is more appropriate for a programming problem than a usage problem, [as discussed in Chapter 9](ch09-03-to-panic-or-not-to-panic#guidelines-for-error-handling). Instead, we’ll use the other technique you learned about in Chapter 9—[returning a `Result`](ch09-02-recoverable-errors-with-result) that indicates either success or an error. #### Returning a `Result` Instead of Calling `panic!` We can instead return a `Result` value that will contain a `Config` instance in the successful case and will describe the problem in the error case. We’re also going to change the function name from `new` to `build` because many programmers expect `new` functions to never fail. When `Config::build` is communicating to `main`, we can use the `Result` type to signal there was a problem. Then we can change `main` to convert an `Err` variant into a more practical error for our users without the surrounding text about `thread 'main'` and `RUST_BACKTRACE` that a call to `panic!` causes. Listing 12-9 shows the changes we need to make to the return value of the function we’re now calling `Config::build` and the body of the function needed to return a `Result`. Note that this won’t compile until we update `main` as well, which we’ll do in the next listing. Filename: src/main.rs ``` use std::env; use std::fs; fn main() { let args: Vec<String> = env::args().collect(); let config = Config::new(&args); println!("Searching for {}", config.query); println!("In file {}", config.file_path); let contents = fs::read_to_string(config.file_path) .expect("Should have been able to read the file"); println!("With text:\n{contents}"); } struct Config { query: String, file_path: String, } impl Config { fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } ``` Listing 12-9: Returning a `Result` from `Config::build` Our `build` function returns a `Result` with a `Config` instance in the success case and a `&'static str` in the error case. Our error values will always be string literals that have the `'static` lifetime. We’ve made two changes in the body of the function: instead of calling `panic!` when the user doesn’t pass enough arguments, we now return an `Err` value, and we’ve wrapped the `Config` return value in an `Ok`. These changes make the function conform to its new type signature. Returning an `Err` value from `Config::build` allows the `main` function to handle the `Result` value returned from the `build` function and exit the process more cleanly in the error case. #### Calling `Config::build` and Handling Errors To handle the error case and print a user-friendly message, we need to update `main` to handle the `Result` being returned by `Config::build`, as shown in Listing 12-10. We’ll also take the responsibility of exiting the command line tool with a nonzero error code away from `panic!` and instead implement it by hand. A nonzero exit status is a convention to signal to the process that called our program that the program exited with an error state. Filename: src/main.rs ``` use std::env; use std::fs; use std::process; fn main() { let args: Vec<String> = env::args().collect(); let config = Config::build(&args).unwrap_or_else(|err| { println!("Problem parsing arguments: {err}"); process::exit(1); }); // --snip-- println!("Searching for {}", config.query); println!("In file {}", config.file_path); let contents = fs::read_to_string(config.file_path) .expect("Should have been able to read the file"); println!("With text:\n{contents}"); } struct Config { query: String, file_path: String, } impl Config { fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } ``` Listing 12-10: Exiting with an error code if building a `Config` fails In this listing, we’ve used a method we haven’t covered in detail yet: `unwrap_or_else`, which is defined on `Result<T, E>` by the standard library. Using `unwrap_or_else` allows us to define some custom, non-`panic!` error handling. If the `Result` is an `Ok` value, this method’s behavior is similar to `unwrap`: it returns the inner value `Ok` is wrapping. However, if the value is an `Err` value, this method calls the code in the *closure*, which is an anonymous function we define and pass as an argument to `unwrap_or_else`. We’ll cover closures in more detail in [Chapter 13](ch13-00-functional-features). For now, you just need to know that `unwrap_or_else` will pass the inner value of the `Err`, which in this case is the static string `"not enough arguments"` that we added in Listing 12-9, to our closure in the argument `err` that appears between the vertical pipes. The code in the closure can then use the `err` value when it runs. We’ve added a new `use` line to bring `process` from the standard library into scope. The code in the closure that will be run in the error case is only two lines: we print the `err` value and then call `process::exit`. The `process::exit` function will stop the program immediately and return the number that was passed as the exit status code. This is similar to the `panic!`-based handling we used in Listing 12-8, but we no longer get all the extra output. Let’s try it: ``` $ cargo run Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished dev [unoptimized + debuginfo] target(s) in 0.48s Running `target/debug/minigrep` Problem parsing arguments: not enough arguments ``` Great! This output is much friendlier for our users. ### Extracting Logic from `main` Now that we’ve finished refactoring the configuration parsing, let’s turn to the program’s logic. As we stated in [“Separation of Concerns for Binary Projects”](#separation-of-concerns-for-binary-projects), we’ll extract a function named `run` that will hold all the logic currently in the `main` function that isn’t involved with setting up configuration or handling errors. When we’re done, `main` will be concise and easy to verify by inspection, and we’ll be able to write tests for all the other logic. Listing 12-11 shows the extracted `run` function. For now, we’re just making the small, incremental improvement of extracting the function. We’re still defining the function in *src/main.rs*. Filename: src/main.rs ``` use std::env; use std::fs; use std::process; fn main() { // --snip-- let args: Vec<String> = env::args().collect(); let config = Config::build(&args).unwrap_or_else(|err| { println!("Problem parsing arguments: {err}"); process::exit(1); }); println!("Searching for {}", config.query); println!("In file {}", config.file_path); run(config); } fn run(config: Config) { let contents = fs::read_to_string(config.file_path) .expect("Should have been able to read the file"); println!("With text:\n{contents}"); } // --snip-- struct Config { query: String, file_path: String, } impl Config { fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } ``` Listing 12-11: Extracting a `run` function containing the rest of the program logic The `run` function now contains all the remaining logic from `main`, starting from reading the file. The `run` function takes the `Config` instance as an argument. #### Returning Errors from the `run` Function With the remaining program logic separated into the `run` function, we can improve the error handling, as we did with `Config::build` in Listing 12-9. Instead of allowing the program to panic by calling `expect`, the `run` function will return a `Result<T, E>` when something goes wrong. This will let us further consolidate the logic around handling errors into `main` in a user-friendly way. Listing 12-12 shows the changes we need to make to the signature and body of `run`. Filename: src/main.rs ``` use std::env; use std::fs; use std::process; use std::error::Error; // --snip-- fn main() { let args: Vec<String> = env::args().collect(); let config = Config::build(&args).unwrap_or_else(|err| { println!("Problem parsing arguments: {err}"); process::exit(1); }); println!("Searching for {}", config.query); println!("In file {}", config.file_path); run(config); } fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; println!("With text:\n{contents}"); Ok(()) } struct Config { query: String, file_path: String, } impl Config { fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } ``` Listing 12-12: Changing the `run` function to return `Result` We’ve made three significant changes here. First, we changed the return type of the `run` function to `Result<(), Box<dyn Error>>`. This function previously returned the unit type, `()`, and we keep that as the value returned in the `Ok` case. For the error type, we used the *trait object* `Box<dyn Error>` (and we’ve brought `std::error::Error` into scope with a `use` statement at the top). We’ll cover trait objects in [Chapter 17](ch17-00-oop). For now, just know that `Box<dyn Error>` means the function will return a type that implements the `Error` trait, but we don’t have to specify what particular type the return value will be. This gives us flexibility to return error values that may be of different types in different error cases. The `dyn` keyword is short for “dynamic.” Second, we’ve removed the call to `expect` in favor of the `?` operator, as we talked about in [Chapter 9](ch09-02-recoverable-errors-with-result#a-shortcut-for-propagating-errors-the--operator). Rather than `panic!` on an error, `?` will return the error value from the current function for the caller to handle. Third, the `run` function now returns an `Ok` value in the success case. We’ve declared the `run` function’s success type as `()` in the signature, which means we need to wrap the unit type value in the `Ok` value. This `Ok(())` syntax might look a bit strange at first, but using `()` like this is the idiomatic way to indicate that we’re calling `run` for its side effects only; it doesn’t return a value we need. When you run this code, it will compile but will display a warning: ``` $ cargo run the poem.txt Compiling minigrep v0.1.0 (file:///projects/minigrep) warning: unused `Result` that must be used --> src/main.rs:19:5 | 19 | run(config); | ^^^^^^^^^^^^ | = note: `#[warn(unused_must_use)]` on by default = note: this `Result` may be an `Err` variant, which should be handled warning: `minigrep` (bin "minigrep") generated 1 warning Finished dev [unoptimized + debuginfo] target(s) in 0.71s Running `target/debug/minigrep the poem.txt` Searching for the In file poem.txt With text: I'm nobody! Who are you? Are you nobody, too? Then there's a pair of us - don't tell! They'd banish us, you know. How dreary to be somebody! How public, like a frog To tell your name the livelong day To an admiring bog! ``` Rust tells us that our code ignored the `Result` value and the `Result` value might indicate that an error occurred. But we’re not checking to see whether or not there was an error, and the compiler reminds us that we probably meant to have some error-handling code here! Let’s rectify that problem now. #### Handling Errors Returned from `run` in `main` We’ll check for errors and handle them using a technique similar to one we used with `Config::build` in Listing 12-10, but with a slight difference: Filename: src/main.rs ``` use std::env; use std::error::Error; use std::fs; use std::process; fn main() { // --snip-- let args: Vec<String> = env::args().collect(); let config = Config::build(&args).unwrap_or_else(|err| { println!("Problem parsing arguments: {err}"); process::exit(1); }); println!("Searching for {}", config.query); println!("In file {}", config.file_path); if let Err(e) = run(config) { println!("Application error: {e}"); process::exit(1); } } fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; println!("With text:\n{contents}"); Ok(()) } struct Config { query: String, file_path: String, } impl Config { fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } ``` We use `if let` rather than `unwrap_or_else` to check whether `run` returns an `Err` value and call `process::exit(1)` if it does. The `run` function doesn’t return a value that we want to `unwrap` in the same way that `Config::build` returns the `Config` instance. Because `run` returns `()` in the success case, we only care about detecting an error, so we don’t need `unwrap_or_else` to return the unwrapped value, which would only be `()`. The bodies of the `if let` and the `unwrap_or_else` functions are the same in both cases: we print the error and exit. ### Splitting Code into a Library Crate Our `minigrep` project is looking good so far! Now we’ll split the *src/main.rs* file and put some code into the *src/lib.rs* file. That way we can test the code and have a *src/main.rs* file with fewer responsibilities. Let’s move all the code that isn’t the `main` function from *src/main.rs* to *src/lib.rs*: * The `run` function definition * The relevant `use` statements * The definition of `Config` * The `Config::build` function definition The contents of *src/lib.rs* should have the signatures shown in Listing 12-13 (we’ve omitted the bodies of the functions for brevity). Note that this won’t compile until we modify *src/main.rs* in Listing 12-14. Filename: src/lib.rs ``` use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, } impl Config { pub fn build(args: &[String]) -> Result<Config, &'static str> { // --snip-- if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { // --snip-- let contents = fs::read_to_string(config.file_path)?; println!("With text:\n{contents}"); Ok(()) } ``` Listing 12-13: Moving `Config` and `run` into *src/lib.rs* We’ve made liberal use of the `pub` keyword: on `Config`, on its fields and its `build` method, and on the `run` function. We now have a library crate that has a public API we can test! Now we need to bring the code we moved to *src/lib.rs* into the scope of the binary crate in *src/main.rs*, as shown in Listing 12-14. Filename: src/main.rs ``` use std::env; use std::process; use minigrep::Config; fn main() { // --snip-- let args: Vec<String> = env::args().collect(); let config = Config::build(&args).unwrap_or_else(|err| { println!("Problem parsing arguments: {err}"); process::exit(1); }); println!("Searching for {}", config.query); println!("In file {}", config.file_path); if let Err(e) = minigrep::run(config) { // --snip-- println!("Application error: {e}"); process::exit(1); } } ``` Listing 12-14: Using the `minigrep` library crate in *src/main.rs* We add a `use minigrep::Config` line to bring the `Config` type from the library crate into the binary crate’s scope, and we prefix the `run` function with our crate name. Now all the functionality should be connected and should work. Run the program with `cargo run` and make sure everything works correctly. Whew! That was a lot of work, but we’ve set ourselves up for success in the future. Now it’s much easier to handle errors, and we’ve made the code more modular. Almost all of our work will be done in *src/lib.rs* from here on out. Let’s take advantage of this newfound modularity by doing something that would have been difficult with the old code but is easy with the new code: we’ll write some tests!
programming_docs
rust Using Trait Objects That Allow for Values of Different Types Using Trait Objects That Allow for Values of Different Types ============================================================ In Chapter 8, we mentioned that one limitation of vectors is that they can store elements of only one type. We created a workaround in Listing 8-9 where we defined a `SpreadsheetCell` enum that had variants to hold integers, floats, and text. This meant we could store different types of data in each cell and still have a vector that represented a row of cells. This is a perfectly good solution when our interchangeable items are a fixed set of types that we know when our code is compiled. However, sometimes we want our library user to be able to extend the set of types that are valid in a particular situation. To show how we might achieve this, we’ll create an example graphical user interface (GUI) tool that iterates through a list of items, calling a `draw` method on each one to draw it to the screen—a common technique for GUI tools. We’ll create a library crate called `gui` that contains the structure of a GUI library. This crate might include some types for people to use, such as `Button` or `TextField`. In addition, `gui` users will want to create their own types that can be drawn: for instance, one programmer might add an `Image` and another might add a `SelectBox`. We won’t implement a fully fledged GUI library for this example but will show how the pieces would fit together. At the time of writing the library, we can’t know and define all the types other programmers might want to create. But we do know that `gui` needs to keep track of many values of different types, and it needs to call a `draw` method on each of these differently typed values. It doesn’t need to know exactly what will happen when we call the `draw` method, just that the value will have that method available for us to call. To do this in a language with inheritance, we might define a class named `Component` that has a method named `draw` on it. The other classes, such as `Button`, `Image`, and `SelectBox`, would inherit from `Component` and thus inherit the `draw` method. They could each override the `draw` method to define their custom behavior, but the framework could treat all of the types as if they were `Component` instances and call `draw` on them. But because Rust doesn’t have inheritance, we need another way to structure the `gui` library to allow users to extend it with new types. ### Defining a Trait for Common Behavior To implement the behavior we want `gui` to have, we’ll define a trait named `Draw` that will have one method named `draw`. Then we can define a vector that takes a *trait object*. A trait object points to both an instance of a type implementing our specified trait and a table used to look up trait methods on that type at runtime. We create a trait object by specifying some sort of pointer, such as a `&` reference or a `Box<T>` smart pointer, then the `dyn` keyword, and then specifying the relevant trait. (We’ll talk about the reason trait objects must use a pointer in Chapter 19 in the section [“Dynamically Sized Types and the `Sized` Trait.”](ch19-04-advanced-types#dynamically-sized-types-and-the-sized-trait)) We can use trait objects in place of a generic or concrete type. Wherever we use a trait object, Rust’s type system will ensure at compile time that any value used in that context will implement the trait object’s trait. Consequently, we don’t need to know all the possible types at compile time. We’ve mentioned that, in Rust, we refrain from calling structs and enums “objects” to distinguish them from other languages’ objects. In a struct or enum, the data in the struct fields and the behavior in `impl` blocks are separated, whereas in other languages, the data and behavior combined into one concept is often labeled an object. However, trait objects *are* more like objects in other languages in the sense that they combine data and behavior. But trait objects differ from traditional objects in that we can’t add data to a trait object. Trait objects aren’t as generally useful as objects in other languages: their specific purpose is to allow abstraction across common behavior. Listing 17-3 shows how to define a trait named `Draw` with one method named `draw`: Filename: src/lib.rs ``` pub trait Draw { fn draw(&self); } ``` Listing 17-3: Definition of the `Draw` trait This syntax should look familiar from our discussions on how to define traits in Chapter 10. Next comes some new syntax: Listing 17-4 defines a struct named `Screen` that holds a vector named `components`. This vector is of type `Box<dyn Draw>`, which is a trait object; it’s a stand-in for any type inside a `Box` that implements the `Draw` trait. Filename: src/lib.rs ``` pub trait Draw { fn draw(&self); } pub struct Screen { pub components: Vec<Box<dyn Draw>>, } ``` Listing 17-4: Definition of the `Screen` struct with a `components` field holding a vector of trait objects that implement the `Draw` trait On the `Screen` struct, we’ll define a method named `run` that will call the `draw` method on each of its `components`, as shown in Listing 17-5: Filename: src/lib.rs ``` pub trait Draw { fn draw(&self); } pub struct Screen { pub components: Vec<Box<dyn Draw>>, } impl Screen { pub fn run(&self) { for component in self.components.iter() { component.draw(); } } } ``` Listing 17-5: A `run` method on `Screen` that calls the `draw` method on each component This works differently from defining a struct that uses a generic type parameter with trait bounds. A generic type parameter can only be substituted with one concrete type at a time, whereas trait objects allow for multiple concrete types to fill in for the trait object at runtime. For example, we could have defined the `Screen` struct using a generic type and a trait bound as in Listing 17-6: Filename: src/lib.rs ``` pub trait Draw { fn draw(&self); } pub struct Screen<T: Draw> { pub components: Vec<T>, } impl<T> Screen<T> where T: Draw, { pub fn run(&self) { for component in self.components.iter() { component.draw(); } } } ``` Listing 17-6: An alternate implementation of the `Screen` struct and its `run` method using generics and trait bounds This restricts us to a `Screen` instance that has a list of components all of type `Button` or all of type `TextField`. If you’ll only ever have homogeneous collections, using generics and trait bounds is preferable because the definitions will be monomorphized at compile time to use the concrete types. On the other hand, with the method using trait objects, one `Screen` instance can hold a `Vec<T>` that contains a `Box<Button>` as well as a `Box<TextField>`. Let’s look at how this works, and then we’ll talk about the runtime performance implications. ### Implementing the Trait Now we’ll add some types that implement the `Draw` trait. We’ll provide the `Button` type. Again, actually implementing a GUI library is beyond the scope of this book, so the `draw` method won’t have any useful implementation in its body. To imagine what the implementation might look like, a `Button` struct might have fields for `width`, `height`, and `label`, as shown in Listing 17-7: Filename: src/lib.rs ``` pub trait Draw { fn draw(&self); } pub struct Screen { pub components: Vec<Box<dyn Draw>>, } impl Screen { pub fn run(&self) { for component in self.components.iter() { component.draw(); } } } pub struct Button { pub width: u32, pub height: u32, pub label: String, } impl Draw for Button { fn draw(&self) { // code to actually draw a button } } ``` Listing 17-7: A `Button` struct that implements the `Draw` trait The `width`, `height`, and `label` fields on `Button` will differ from the fields on other components; for example, a `TextField` type might have those same fields plus a `placeholder` field. Each of the types we want to draw on the screen will implement the `Draw` trait but will use different code in the `draw` method to define how to draw that particular type, as `Button` has here (without the actual GUI code, as mentioned). The `Button` type, for instance, might have an additional `impl` block containing methods related to what happens when a user clicks the button. These kinds of methods won’t apply to types like `TextField`. If someone using our library decides to implement a `SelectBox` struct that has `width`, `height`, and `options` fields, they implement the `Draw` trait on the `SelectBox` type as well, as shown in Listing 17-8: Filename: src/main.rs ``` use gui::Draw; struct SelectBox { width: u32, height: u32, options: Vec<String>, } impl Draw for SelectBox { fn draw(&self) { // code to actually draw a select box } } fn main() {} ``` Listing 17-8: Another crate using `gui` and implementing the `Draw` trait on a `SelectBox` struct Our library’s user can now write their `main` function to create a `Screen` instance. To the `Screen` instance, they can add a `SelectBox` and a `Button` by putting each in a `Box<T>` to become a trait object. They can then call the `run` method on the `Screen` instance, which will call `draw` on each of the components. Listing 17-9 shows this implementation: Filename: src/main.rs ``` use gui::Draw; struct SelectBox { width: u32, height: u32, options: Vec<String>, } impl Draw for SelectBox { fn draw(&self) { // code to actually draw a select box } } use gui::{Button, Screen}; fn main() { let screen = Screen { components: vec![ Box::new(SelectBox { width: 75, height: 10, options: vec![ String::from("Yes"), String::from("Maybe"), String::from("No"), ], }), Box::new(Button { width: 50, height: 10, label: String::from("OK"), }), ], }; screen.run(); } ``` Listing 17-9: Using trait objects to store values of different types that implement the same trait When we wrote the library, we didn’t know that someone might add the `SelectBox` type, but our `Screen` implementation was able to operate on the new type and draw it because `SelectBox` implements the `Draw` trait, which means it implements the `draw` method. This concept—of being concerned only with the messages a value responds to rather than the value’s concrete type—is similar to the concept of *duck typing* in dynamically typed languages: if it walks like a duck and quacks like a duck, then it must be a duck! In the implementation of `run` on `Screen` in Listing 17-5, `run` doesn’t need to know what the concrete type of each component is. It doesn’t check whether a component is an instance of a `Button` or a `SelectBox`, it just calls the `draw` method on the component. By specifying `Box<dyn Draw>` as the type of the values in the `components` vector, we’ve defined `Screen` to need values that we can call the `draw` method on. The advantage of using trait objects and Rust’s type system to write code similar to code using duck typing is that we never have to check whether a value implements a particular method at runtime or worry about getting errors if a value doesn’t implement a method but we call it anyway. Rust won’t compile our code if the values don’t implement the traits that the trait objects need. For example, Listing 17-10 shows what happens if we try to create a `Screen` with a `String` as a component: Filename: src/main.rs ``` use gui::Screen; fn main() { let screen = Screen { components: vec![Box::new(String::from("Hi"))], }; screen.run(); } ``` Listing 17-10: Attempting to use a type that doesn’t implement the trait object’s trait We’ll get this error because `String` doesn’t implement the `Draw` trait: ``` $ cargo run Compiling gui v0.1.0 (file:///projects/gui) error[E0277]: the trait bound `String: Draw` is not satisfied --> src/main.rs:5:26 | 5 | components: vec![Box::new(String::from("Hi"))], | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Draw` is not implemented for `String` | = help: the trait `Draw` is implemented for `Button` = note: required for the cast to the object type `dyn Draw` For more information about this error, try `rustc --explain E0277`. error: could not compile `gui` due to previous error ``` This error lets us know that either we’re passing something to `Screen` we didn’t mean to pass and so should pass a different type or we should implement `Draw` on `String` so that `Screen` is able to call `draw` on it. ### Trait Objects Perform Dynamic Dispatch Recall in the [“Performance of Code Using Generics”](ch10-01-syntax#performance-of-code-using-generics) section in Chapter 10 our discussion on the monomorphization process performed by the compiler when we use trait bounds on generics: the compiler generates nongeneric implementations of functions and methods for each concrete type that we use in place of a generic type parameter. The code that results from monomorphization is doing *static dispatch*, which is when the compiler knows what method you’re calling at compile time. This is opposed to *dynamic dispatch*, which is when the compiler can’t tell at compile time which method you’re calling. In dynamic dispatch cases, the compiler emits code that at runtime will figure out which method to call. When we use trait objects, Rust must use dynamic dispatch. The compiler doesn’t know all the types that might be used with the code that’s using trait objects, so it doesn’t know which method implemented on which type to call. Instead, at runtime, Rust uses the pointers inside the trait object to know which method to call. This lookup incurs a runtime cost that doesn’t occur with static dispatch. Dynamic dispatch also prevents the compiler from choosing to inline a method’s code, which in turn prevents some optimizations. However, we did get extra flexibility in the code that we wrote in Listing 17-5 and were able to support in Listing 17-9, so it’s a trade-off to consider. rust Advanced Types Advanced Types ============== The Rust type system has some features that we’ve so far mentioned but haven’t yet discussed. We’ll start by discussing newtypes in general as we examine why newtypes are useful as types. Then we’ll move on to type aliases, a feature similar to newtypes but with slightly different semantics. We’ll also discuss the `!` type and dynamically sized types. ### Using the Newtype Pattern for Type Safety and Abstraction > Note: This section assumes you’ve read the earlier section [“Using the Newtype Pattern to Implement External Traits on External Types.”](ch19-03-advanced-traits#using-the-newtype-pattern-to-implement-external-traits-on-external-types) > > The newtype pattern is also useful for tasks beyond those we’ve discussed so far, including statically enforcing that values are never confused and indicating the units of a value. You saw an example of using newtypes to indicate units in Listing 19-15: recall that the `Millimeters` and `Meters` structs wrapped `u32` values in a newtype. If we wrote a function with a parameter of type `Millimeters`, we couldn’t compile a program that accidentally tried to call that function with a value of type `Meters` or a plain `u32`. We can also use the newtype pattern to abstract away some implementation details of a type: the new type can expose a public API that is different from the API of the private inner type. Newtypes can also hide internal implementation. For example, we could provide a `People` type to wrap a `HashMap<i32, String>` that stores a person’s ID associated with their name. Code using `People` would only interact with the public API we provide, such as a method to add a name string to the `People` collection; that code wouldn’t need to know that we assign an `i32` ID to names internally. The newtype pattern is a lightweight way to achieve encapsulation to hide implementation details, which we discussed in the [“Encapsulation that Hides Implementation Details”](ch17-01-what-is-oo#encapsulation-that-hides-implementation-details) section of Chapter 17. ### Creating Type Synonyms with Type Aliases Rust provides the ability to declare a *type alias* to give an existing type another name. For this we use the `type` keyword. For example, we can create the alias `Kilometers` to `i32` like so: ``` fn main() { type Kilometers = i32; let x: i32 = 5; let y: Kilometers = 5; println!("x + y = {}", x + y); } ``` Now, the alias `Kilometers` is a *synonym* for `i32`; unlike the `Millimeters` and `Meters` types we created in Listing 19-15, `Kilometers` is not a separate, new type. Values that have the type `Kilometers` will be treated the same as values of type `i32`: ``` fn main() { type Kilometers = i32; let x: i32 = 5; let y: Kilometers = 5; println!("x + y = {}", x + y); } ``` Because `Kilometers` and `i32` are the same type, we can add values of both types and we can pass `Kilometers` values to functions that take `i32` parameters. However, using this method, we don’t get the type checking benefits that we get from the newtype pattern discussed earlier. In other words, if we mix up `Kilometers` and `i32` values somewhere, the compiler will not give us an error. The main use case for type synonyms is to reduce repetition. For example, we might have a lengthy type like this: ``` Box<dyn Fn() + Send + 'static> ``` Writing this lengthy type in function signatures and as type annotations all over the code can be tiresome and error prone. Imagine having a project full of code like that in Listing 19-24. ``` fn main() { let f: Box<dyn Fn() + Send + 'static> = Box::new(|| println!("hi")); fn takes_long_type(f: Box<dyn Fn() + Send + 'static>) { // --snip-- } fn returns_long_type() -> Box<dyn Fn() + Send + 'static> { // --snip-- Box::new(|| ()) } } ``` Listing 19-24: Using a long type in many places A type alias makes this code more manageable by reducing the repetition. In Listing 19-25, we’ve introduced an alias named `Thunk` for the verbose type and can replace all uses of the type with the shorter alias `Thunk`. ``` fn main() { type Thunk = Box<dyn Fn() + Send + 'static>; let f: Thunk = Box::new(|| println!("hi")); fn takes_long_type(f: Thunk) { // --snip-- } fn returns_long_type() -> Thunk { // --snip-- Box::new(|| ()) } } ``` Listing 19-25: Introducing a type alias `Thunk` to reduce repetition This code is much easier to read and write! Choosing a meaningful name for a type alias can help communicate your intent as well (*thunk* is a word for code to be evaluated at a later time, so it’s an appropriate name for a closure that gets stored). Type aliases are also commonly used with the `Result<T, E>` type for reducing repetition. Consider the `std::io` module in the standard library. I/O operations often return a `Result<T, E>` to handle situations when operations fail to work. This library has a `std::io::Error` struct that represents all possible I/O errors. Many of the functions in `std::io` will be returning `Result<T, E>` where the `E` is `std::io::Error`, such as these functions in the `Write` trait: ``` use std::fmt; use std::io::Error; pub trait Write { fn write(&mut self, buf: &[u8]) -> Result<usize, Error>; fn flush(&mut self) -> Result<(), Error>; fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>; fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Error>; } ``` The `Result<..., Error>` is repeated a lot. As such, `std::io` has this type alias declaration: ``` use std::fmt; type Result<T> = std::result::Result<T, std::io::Error>; pub trait Write { fn write(&mut self, buf: &[u8]) -> Result<usize>; fn flush(&mut self) -> Result<()>; fn write_all(&mut self, buf: &[u8]) -> Result<()>; fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()>; } ``` Because this declaration is in the `std::io` module, we can use the fully qualified alias `std::io::Result<T>`; that is, a `Result<T, E>` with the `E` filled in as `std::io::Error`. The `Write` trait function signatures end up looking like this: ``` use std::fmt; type Result<T> = std::result::Result<T, std::io::Error>; pub trait Write { fn write(&mut self, buf: &[u8]) -> Result<usize>; fn flush(&mut self) -> Result<()>; fn write_all(&mut self, buf: &[u8]) -> Result<()>; fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()>; } ``` The type alias helps in two ways: it makes code easier to write *and* it gives us a consistent interface across all of `std::io`. Because it’s an alias, it’s just another `Result<T, E>`, which means we can use any methods that work on `Result<T, E>` with it, as well as special syntax like the `?` operator. ### The Never Type that Never Returns Rust has a special type named `!` that’s known in type theory lingo as the *empty type* because it has no values. We prefer to call it the *never type* because it stands in the place of the return type when a function will never return. Here is an example: ``` fn bar() -> ! { // --snip-- panic!(); } ``` This code is read as “the function `bar` returns never.” Functions that return never are called *diverging functions*. We can’t create values of the type `!` so `bar` can never possibly return. But what use is a type you can never create values for? Recall the code from Listing 2-5, part of the number guessing game; we’ve reproduced a bit of it here in Listing 19-26. ``` use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); loop { println!("Please input your guess."); let mut guess = String::new(); // --snip-- io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("You guessed: {guess}"); // --snip-- match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } } ``` Listing 19-26: A `match` with an arm that ends in `continue` At the time, we skipped over some details in this code. In Chapter 6 in [“The `match` Control Flow Operator”](ch06-02-match#the-match-control-flow-operator) section, we discussed that `match` arms must all return the same type. So, for example, the following code doesn’t work: ``` fn main() { let guess = "3"; let guess = match guess.trim().parse() { Ok(_) => 5, Err(_) => "hello", }; } ``` The type of `guess` in this code would have to be an integer *and* a string, and Rust requires that `guess` have only one type. So what does `continue` return? How were we allowed to return a `u32` from one arm and have another arm that ends with `continue` in Listing 19-26? As you might have guessed, `continue` has a `!` value. That is, when Rust computes the type of `guess`, it looks at both match arms, the former with a value of `u32` and the latter with a `!` value. Because `!` can never have a value, Rust decides that the type of `guess` is `u32`. The formal way of describing this behavior is that expressions of type `!` can be coerced into any other type. We’re allowed to end this `match` arm with `continue` because `continue` doesn’t return a value; instead, it moves control back to the top of the loop, so in the `Err` case, we never assign a value to `guess`. The never type is useful with the `panic!` macro as well. Recall the `unwrap` function that we call on `Option<T>` values to produce a value or panic with this definition: ``` enum Option<T> { Some(T), None, } use crate::Option::*; impl<T> Option<T> { pub fn unwrap(self) -> T { match self { Some(val) => val, None => panic!("called `Option::unwrap()` on a `None` value"), } } } ``` In this code, the same thing happens as in the `match` in Listing 19-26: Rust sees that `val` has the type `T` and `panic!` has the type `!`, so the result of the overall `match` expression is `T`. This code works because `panic!` doesn’t produce a value; it ends the program. In the `None` case, we won’t be returning a value from `unwrap`, so this code is valid. One final expression that has the type `!` is a `loop`: ``` fn main() { print!("forever "); loop { print!("and ever "); } } ``` Here, the loop never ends, so `!` is the value of the expression. However, this wouldn’t be true if we included a `break`, because the loop would terminate when it got to the `break`. ### Dynamically Sized Types and the `Sized` Trait Rust needs to know certain details about its types, such as how much space to allocate for a value of a particular type. This leaves one corner of its type system a little confusing at first: the concept of *dynamically sized types*. Sometimes referred to as *DSTs* or *unsized types*, these types let us write code using values whose size we can know only at runtime. Let’s dig into the details of a dynamically sized type called `str`, which we’ve been using throughout the book. That’s right, not `&str`, but `str` on its own, is a DST. We can’t know how long the string is until runtime, meaning we can’t create a variable of type `str`, nor can we take an argument of type `str`. Consider the following code, which does not work: ``` fn main() { let s1: str = "Hello there!"; let s2: str = "How's it going?"; } ``` Rust needs to know how much memory to allocate for any value of a particular type, and all values of a type must use the same amount of memory. If Rust allowed us to write this code, these two `str` values would need to take up the same amount of space. But they have different lengths: `s1` needs 12 bytes of storage and `s2` needs 15. This is why it’s not possible to create a variable holding a dynamically sized type. So what do we do? In this case, you already know the answer: we make the types of `s1` and `s2` a `&str` rather than a `str`. Recall from the [“String Slices”](ch04-03-slices#string-slices) section of Chapter 4 that the slice data structure just stores the starting position and the length of the slice. So although a `&T` is a single value that stores the memory address of where the `T` is located, a `&str` is *two* values: the address of the `str` and its length. As such, we can know the size of a `&str` value at compile time: it’s twice the length of a `usize`. That is, we always know the size of a `&str`, no matter how long the string it refers to is. In general, this is the way in which dynamically sized types are used in Rust: they have an extra bit of metadata that stores the size of the dynamic information. The golden rule of dynamically sized types is that we must always put values of dynamically sized types behind a pointer of some kind. We can combine `str` with all kinds of pointers: for example, `Box<str>` or `Rc<str>`. In fact, you’ve seen this before but with a different dynamically sized type: traits. Every trait is a dynamically sized type we can refer to by using the name of the trait. In Chapter 17 in the [“Using Trait Objects That Allow for Values of Different Types”](ch17-02-trait-objects#using-trait-objects-that-allow-for-values-of-different-types) section, we mentioned that to use traits as trait objects, we must put them behind a pointer, such as `&dyn Trait` or `Box<dyn Trait>` (`Rc<dyn Trait>` would work too). To work with DSTs, Rust provides the `Sized` trait to determine whether or not a type’s size is known at compile time. This trait is automatically implemented for everything whose size is known at compile time. In addition, Rust implicitly adds a bound on `Sized` to every generic function. That is, a generic function definition like this: ``` fn generic<T>(t: T) { // --snip-- } ``` is actually treated as though we had written this: ``` fn generic<T: Sized>(t: T) { // --snip-- } ``` By default, generic functions will work only on types that have a known size at compile time. However, you can use the following special syntax to relax this restriction: ``` fn generic<T: ?Sized>(t: &T) { // --snip-- } ``` A trait bound on `?Sized` means “`T` may or may not be `Sized`” and this notation overrides the default that generic types must have a known size at compile time. The `?Trait` syntax with this meaning is only available for `Sized`, not any other traits. Also note that we switched the type of the `t` parameter from `T` to `&T`. Because the type might not be `Sized`, we need to use it behind some kind of pointer. In this case, we’ve chosen a reference. Next, we’ll talk about functions and closures!
programming_docs
rust Recoverable Errors with Result Recoverable Errors with `Result` ================================ Most errors aren’t serious enough to require the program to stop entirely. Sometimes, when a function fails, it’s for a reason that you can easily interpret and respond to. For example, if you try to open a file and that operation fails because the file doesn’t exist, you might want to create the file instead of terminating the process. Recall from [“Handling Potential Failure with the `Result` Type”](ch02-00-guessing-game-tutorial#handling-potential-failure-with-the-result-type) in Chapter 2 that the `Result` enum is defined as having two variants, `Ok` and `Err`, as follows: ``` #![allow(unused)] fn main() { enum Result<T, E> { Ok(T), Err(E), } } ``` The `T` and `E` are generic type parameters: we’ll discuss generics in more detail in Chapter 10. What you need to know right now is that `T` represents the type of the value that will be returned in a success case within the `Ok` variant, and `E` represents the type of the error that will be returned in a failure case within the `Err` variant. Because `Result` has these generic type parameters, we can use the `Result` type and the functions defined on it in many different situations where the successful value and error value we want to return may differ. Let’s call a function that returns a `Result` value because the function could fail. In Listing 9-3 we try to open a file. Filename: src/main.rs ``` use std::fs::File; fn main() { let greeting_file_result = File::open("hello.txt"); } ``` Listing 9-3: Opening a file The return type of `File::open` is a `Result<T, E>`. The generic parameter `T` has been filled in by the implementation of `File::open` with the type of the success value, `std::fs::File`, which is a file handle. The type of `E` used in the error value is `std::io::Error`. This return type means the call to `File::open` might succeed and return a file handle that we can read from or write to. The function call also might fail: for example, the file might not exist, or we might not have permission to access the file. The `File::open` function needs to have a way to tell us whether it succeeded or failed and at the same time give us either the file handle or error information. This information is exactly what the `Result` enum conveys. In the case where `File::open` succeeds, the value in the variable `greeting_file_result` will be an instance of `Ok` that contains a file handle. In the case where it fails, the value in `greeting_file_result` will be an instance of `Err` that contains more information about the kind of error that happened. We need to add to the code in Listing 9-3 to take different actions depending on the value `File::open` returns. Listing 9-4 shows one way to handle the `Result` using a basic tool, the `match` expression that we discussed in Chapter 6. Filename: src/main.rs ``` use std::fs::File; fn main() { let greeting_file_result = File::open("hello.txt"); let greeting_file = match greeting_file_result { Ok(file) => file, Err(error) => panic!("Problem opening the file: {:?}", error), }; } ``` Listing 9-4: Using a `match` expression to handle the `Result` variants that might be returned Note that, like the `Option` enum, the `Result` enum and its variants have been brought into scope by the prelude, so we don’t need to specify `Result::` before the `Ok` and `Err` variants in the `match` arms. When the result is `Ok`, this code will return the inner `file` value out of the `Ok` variant, and we then assign that file handle value to the variable `greeting_file`. After the `match`, we can use the file handle for reading or writing. The other arm of the `match` handles the case where we get an `Err` value from `File::open`. In this example, we’ve chosen to call the `panic!` macro. If there’s no file named *hello.txt* in our current directory and we run this code, we’ll see the following output from the `panic!` macro: ``` $ cargo run Compiling error-handling v0.1.0 (file:///projects/error-handling) Finished dev [unoptimized + debuginfo] target(s) in 0.73s Running `target/debug/error-handling` thread 'main' panicked at 'Problem opening the file: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:8:23 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` As usual, this output tells us exactly what has gone wrong. ### Matching on Different Errors The code in Listing 9-4 will `panic!` no matter why `File::open` failed. However, we want to take different actions for different failure reasons: if `File::open` failed because the file doesn’t exist, we want to create the file and return the handle to the new file. If `File::open` failed for any other reason—for example, because we didn’t have permission to open the file—we still want the code to `panic!` in the same way as it did in Listing 9-4. For this we add an inner `match` expression, shown in Listing 9-5. Filename: src/main.rs ``` use std::fs::File; use std::io::ErrorKind; fn main() { let greeting_file_result = File::open("hello.txt"); let greeting_file = match greeting_file_result { Ok(file) => file, Err(error) => match error.kind() { ErrorKind::NotFound => match File::create("hello.txt") { Ok(fc) => fc, Err(e) => panic!("Problem creating the file: {:?}", e), }, other_error => { panic!("Problem opening the file: {:?}", other_error); } }, }; } ``` Listing 9-5: Handling different kinds of errors in different ways The type of the value that `File::open` returns inside the `Err` variant is `io::Error`, which is a struct provided by the standard library. This struct has a method `kind` that we can call to get an `io::ErrorKind` value. The enum `io::ErrorKind` is provided by the standard library and has variants representing the different kinds of errors that might result from an `io` operation. The variant we want to use is `ErrorKind::NotFound`, which indicates the file we’re trying to open doesn’t exist yet. So we match on `greeting_file_result`, but we also have an inner match on `error.kind()`. The condition we want to check in the inner match is whether the value returned by `error.kind()` is the `NotFound` variant of the `ErrorKind` enum. If it is, we try to create the file with `File::create`. However, because `File::create` could also fail, we need a second arm in the inner `match` expression. When the file can’t be created, a different error message is printed. The second arm of the outer `match` stays the same, so the program panics on any error besides the missing file error. > ### Alternatives to Using `match` with `Result<T, E>` > > That’s a lot of `match`! The `match` expression is very useful but also very much a primitive. In Chapter 13, you’ll learn about closures, which are used with many of the methods defined on `Result<T, E>`. These methods can be more concise than using `match` when handling `Result<T, E>` values in your code. > > For example, here’s another way to write the same logic as shown in Listing 9-5, this time using closures and the `unwrap_or_else` method: > > > ``` > use std::fs::File; > use std::io::ErrorKind; > > fn main() { > let greeting_file = File::open("hello.txt").unwrap_or_else(|error| { > if error.kind() == ErrorKind::NotFound { > File::create("hello.txt").unwrap_or_else(|error| { > panic!("Problem creating the file: {:?}", error); > }) > } else { > panic!("Problem opening the file: {:?}", error); > } > }); > } > > ``` > Although this code has the same behavior as Listing 9-5, it doesn’t contain any `match` expressions and is cleaner to read. Come back to this example after you’ve read Chapter 13, and look up the `unwrap_or_else` method in the standard library documentation. Many more of these methods can clean up huge nested `match` expressions when you’re dealing with errors. > > ### Shortcuts for Panic on Error: `unwrap` and `expect` Using `match` works well enough, but it can be a bit verbose and doesn’t always communicate intent well. The `Result<T, E>` type has many helper methods defined on it to do various, more specific tasks. The `unwrap` method is a shortcut method implemented just like the `match` expression we wrote in Listing 9-4. If the `Result` value is the `Ok` variant, `unwrap` will return the value inside the `Ok`. If the `Result` is the `Err` variant, `unwrap` will call the `panic!` macro for us. Here is an example of `unwrap` in action: Filename: src/main.rs ``` use std::fs::File; fn main() { let greeting_file = File::open("hello.txt").unwrap(); } ``` If we run this code without a *hello.txt* file, we’ll see an error message from the `panic!` call that the `unwrap` method makes: ``` thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:4:49 ``` Similarly, the `expect` method lets us also choose the `panic!` error message. Using `expect` instead of `unwrap` and providing good error messages can convey your intent and make tracking down the source of a panic easier. The syntax of `expect` looks like this: Filename: src/main.rs ``` use std::fs::File; fn main() { let greeting_file = File::open("hello.txt") .expect("hello.txt should be included in this project"); } ``` We use `expect` in the same way as `unwrap`: to return the file handle or call the `panic!` macro. The error message used by `expect` in its call to `panic!` will be the parameter that we pass to `expect`, rather than the default `panic!` message that `unwrap` uses. Here’s what it looks like: ``` thread 'main' panicked at 'hello.txt should be included in this project: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:5:10 ``` In production-quality code, most Rustaceans choose `expect` rather than `unwrap` and give more context about why the operation is expected to always succeed. That way, if your assumptions are ever proven wrong, you have more information to use in debugging. ### Propagating Errors When a function’s implementation calls something that might fail, instead of handling the error within the function itself, you can return the error to the calling code so that it can decide what to do. This is known as *propagating* the error and gives more control to the calling code, where there might be more information or logic that dictates how the error should be handled than what you have available in the context of your code. For example, Listing 9-6 shows a function that reads a username from a file. If the file doesn’t exist or can’t be read, this function will return those errors to the code that called the function. Filename: src/main.rs ``` #![allow(unused)] fn main() { use std::fs::File; use std::io::{self, Read}; fn read_username_from_file() -> Result<String, io::Error> { let username_file_result = File::open("hello.txt"); let mut username_file = match username_file_result { Ok(file) => file, Err(e) => return Err(e), }; let mut username = String::new(); match username_file.read_to_string(&mut username) { Ok(_) => Ok(username), Err(e) => Err(e), } } } ``` Listing 9-6: A function that returns errors to the calling code using `match` This function can be written in a much shorter way, but we’re going to start by doing a lot of it manually in order to explore error handling; at the end, we’ll show the shorter way. Let’s look at the return type of the function first: `Result<String, io::Error>`. This means the function is returning a value of the type `Result<T, E>` where the generic parameter `T` has been filled in with the concrete type `String`, and the generic type `E` has been filled in with the concrete type `io::Error`. If this function succeeds without any problems, the code that calls this function will receive an `Ok` value that holds a `String`—the username that this function read from the file. If this function encounters any problems, the calling code will receive an `Err` value that holds an instance of `io::Error` that contains more information about what the problems were. We chose `io::Error` as the return type of this function because that happens to be the type of the error value returned from both of the operations we’re calling in this function’s body that might fail: the `File::open` function and the `read_to_string` method. The body of the function starts by calling the `File::open` function. Then we handle the `Result` value with a `match` similar to the `match` in Listing 9-4. If `File::open` succeeds, the file handle in the pattern variable `file` becomes the value in the mutable variable `username_file` and the function continues. In the `Err` case, instead of calling `panic!`, we use the `return` keyword to return early out of the function entirely and pass the error value from `File::open`, now in the pattern variable `e`, back to the calling code as this function’s error value. So if we have a file handle in `username_file`, the function then creates a new `String` in variable `username` and calls the `read_to_string` method on the file handle in `username_file` to read the contents of the file into `username`. The `read_to_string` method also returns a `Result` because it might fail, even though `File::open` succeeded. So we need another `match` to handle that `Result`: if `read_to_string` succeeds, then our function has succeeded, and we return the username from the file that’s now in `username` wrapped in an `Ok`. If `read_to_string` fails, we return the error value in the same way that we returned the error value in the `match` that handled the return value of `File::open`. However, we don’t need to explicitly say `return`, because this is the last expression in the function. The code that calls this code will then handle getting either an `Ok` value that contains a username or an `Err` value that contains an `io::Error`. It’s up to the calling code to decide what to do with those values. If the calling code gets an `Err` value, it could call `panic!` and crash the program, use a default username, or look up the username from somewhere other than a file, for example. We don’t have enough information on what the calling code is actually trying to do, so we propagate all the success or error information upward for it to handle appropriately. This pattern of propagating errors is so common in Rust that Rust provides the question mark operator `?` to make this easier. #### A Shortcut for Propagating Errors: the `?` Operator Listing 9-7 shows an implementation of `read_username_from_file` that has the same functionality as in Listing 9-6, but this implementation uses the `?` operator. Filename: src/main.rs ``` #![allow(unused)] fn main() { use std::fs::File; use std::io; use std::io::Read; fn read_username_from_file() -> Result<String, io::Error> { let mut username_file = File::open("hello.txt")?; let mut username = String::new(); username_file.read_to_string(&mut username)?; Ok(username) } } ``` Listing 9-7: A function that returns errors to the calling code using the `?` operator The `?` placed after a `Result` value is defined to work in almost the same way as the `match` expressions we defined to handle the `Result` values in Listing 9-6. If the value of the `Result` is an `Ok`, the value inside the `Ok` will get returned from this expression, and the program will continue. If the value is an `Err`, the `Err` will be returned from the whole function as if we had used the `return` keyword so the error value gets propagated to the calling code. There is a difference between what the `match` expression from Listing 9-6 does and what the `?` operator does: error values that have the `?` operator called on them go through the `from` function, defined in the `From` trait in the standard library, which is used to convert values from one type into another. When the `?` operator calls the `from` function, the error type received is converted into the error type defined in the return type of the current function. This is useful when a function returns one error type to represent all the ways a function might fail, even if parts might fail for many different reasons. For example, we could change the `read_username_from_file` function in Listing 9-7 to return a custom error type named `OurError` that we define. If we also define `impl From<io::Error> for OurError` to construct an instance of `OurError` from an `io::Error`, then the `?` operator calls in the body of `read_username_from_file` will call `from` and convert the error types without needing to add any more code to the function. In the context of Listing 9-7, the `?` at the end of the `File::open` call will return the value inside an `Ok` to the variable `username_file`. If an error occurs, the `?` operator will return early out of the whole function and give any `Err` value to the calling code. The same thing applies to the `?` at the end of the `read_to_string` call. The `?` operator eliminates a lot of boilerplate and makes this function’s implementation simpler. We could even shorten this code further by chaining method calls immediately after the `?`, as shown in Listing 9-8. Filename: src/main.rs ``` #![allow(unused)] fn main() { use std::fs::File; use std::io; use std::io::Read; fn read_username_from_file() -> Result<String, io::Error> { let mut username = String::new(); File::open("hello.txt")?.read_to_string(&mut username)?; Ok(username) } } ``` Listing 9-8: Chaining method calls after the `?` operator We’ve moved the creation of the new `String` in `username` to the beginning of the function; that part hasn’t changed. Instead of creating a variable `username_file`, we’ve chained the call to `read_to_string` directly onto the result of `File::open("hello.txt")?`. We still have a `?` at the end of the `read_to_string` call, and we still return an `Ok` value containing `username` when both `File::open` and `read_to_string` succeed rather than returning errors. The functionality is again the same as in Listing 9-6 and Listing 9-7; this is just a different, more ergonomic way to write it. Listing 9-9 shows a way to make this even shorter using `fs::read_to_string`. Filename: src/main.rs ``` #![allow(unused)] fn main() { use std::fs; use std::io; fn read_username_from_file() -> Result<String, io::Error> { fs::read_to_string("hello.txt") } } ``` Listing 9-9: Using `fs::read_to_string` instead of opening and then reading the file Reading a file into a string is a fairly common operation, so the standard library provides the convenient `fs::read_to_string` function that opens the file, creates a new `String`, reads the contents of the file, puts the contents into that `String`, and returns it. Of course, using `fs::read_to_string` doesn’t give us the opportunity to explain all the error handling, so we did it the longer way first. #### Where The `?` Operator Can Be Used The `?` operator can only be used in functions whose return type is compatible with the value the `?` is used on. This is because the `?` operator is defined to perform an early return of a value out of the function, in the same manner as the `match` expression we defined in Listing 9-6. In Listing 9-6, the `match` was using a `Result` value, and the early return arm returned an `Err(e)` value. The return type of the function has to be a `Result` so that it’s compatible with this `return`. In Listing 9-10, let’s look at the error we’ll get if we use the `?` operator in a `main` function with a return type incompatible with the type of the value we use `?` on: Filename: src/main.rs ``` use std::fs::File; fn main() { let greeting_file = File::open("hello.txt")?; } ``` Listing 9-10: Attempting to use the `?` in the `main` function that returns `()` won’t compile This code opens a file, which might fail. The `?` operator follows the `Result` value returned by `File::open`, but this `main` function has the return type of `()`, not `Result`. When we compile this code, we get the following error message: ``` $ cargo run Compiling error-handling v0.1.0 (file:///projects/error-handling) error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) --> src/main.rs:4:48 | 3 | / fn main() { 4 | | let greeting_file = File::open("hello.txt")?; | | ^ cannot use the `?` operator in a function that returns `()` 5 | | } | |_- this function should return `Result` or `Option` to accept `?` | = help: the trait `FromResidual<Result<Infallible, std::io::Error>>` is not implemented for `()` For more information about this error, try `rustc --explain E0277`. error: could not compile `error-handling` due to previous error ``` This error points out that we’re only allowed to use the `?` operator in a function that returns `Result`, `Option`, or another type that implements `FromResidual`. To fix the error, you have two choices. One choice is to change the return type of your function to be compatible with the value you’re using the `?` operator on as long as you have no restrictions preventing that. The other technique is to use a `match` or one of the `Result<T, E>` methods to handle the `Result<T, E>` in whatever way is appropriate. The error message also mentioned that `?` can be used with `Option<T>` values as well. As with using `?` on `Result`, you can only use `?` on `Option` in a function that returns an `Option`. The behavior of the `?` operator when called on an `Option<T>` is similar to its behavior when called on a `Result<T, E>`: if the value is `None`, the `None` will be returned early from the function at that point. If the value is `Some`, the value inside the `Some` is the resulting value of the expression and the function continues. Listing 9-11 has an example of a function that finds the last character of the first line in the given text: ``` fn last_char_of_first_line(text: &str) -> Option<char> { text.lines().next()?.chars().last() } fn main() { assert_eq!( last_char_of_first_line("Hello, world\nHow are you today?"), Some('d') ); assert_eq!(last_char_of_first_line(""), None); assert_eq!(last_char_of_first_line("\nhi"), None); } ``` Listing 9-11: Using the `?` operator on an `Option<T>` value This function returns `Option<char>` because it’s possible that there is a character there, but it’s also possible that there isn’t. This code takes the `text` string slice argument and calls the `lines` method on it, which returns an iterator over the lines in the string. Because this function wants to examine the first line, it calls `next` on the iterator to get the first value from the iterator. If `text` is the empty string, this call to `next` will return `None`, in which case we use `?` to stop and return `None` from `last_char_of_first_line`. If `text` is not the empty string, `next` will return a `Some` value containing a string slice of the first line in `text`. The `?` extracts the string slice, and we can call `chars` on that string slice to get an iterator of its characters. We’re interested in the last character in this first line, so we call `last` to return the last item in the iterator. This is an `Option` because it’s possible that the first line is the empty string, for example if `text` starts with a blank line but has characters on other lines, as in `"\nhi"`. However, if there is a last character on the first line, it will be returned in the `Some` variant. The `?` operator in the middle gives us a concise way to express this logic, allowing us to implement the function in one line. If we couldn’t use the `?` operator on `Option`, we’d have to implement this logic using more method calls or a `match` expression. Note that you can use the `?` operator on a `Result` in a function that returns `Result`, and you can use the `?` operator on an `Option` in a function that returns `Option`, but you can’t mix and match. The `?` operator won’t automatically convert a `Result` to an `Option` or vice versa; in those cases, you can use methods like the `ok` method on `Result` or the `ok_or` method on `Option` to do the conversion explicitly. So far, all the `main` functions we’ve used return `()`. The `main` function is special because it’s the entry and exit point of executable programs, and there are restrictions on what its return type can be for the programs to behave as expected. Luckily, `main` can also return a `Result<(), E>`. Listing 9-12 has the code from Listing 9-10 but we’ve changed the return type of `main` to be `Result<(), Box<dyn Error>>` and added a return value `Ok(())` to the end. This code will now compile: ``` use std::error::Error; use std::fs::File; fn main() -> Result<(), Box<dyn Error>> { let greeting_file = File::open("hello.txt")?; Ok(()) } ``` Listing 9-12: Changing `main` to return `Result<(), E>` allows the use of the `?` operator on `Result` values The `Box<dyn Error>` type is a *trait object*, which we’ll talk about in the [“Using Trait Objects that Allow for Values of Different Types”](ch17-02-trait-objects#using-trait-objects-that-allow-for-values-of-different-types) section in Chapter 17. For now, you can read `Box<dyn Error>` to mean “any kind of error.” Using `?` on a `Result` value in a `main` function with the error type `Box<dyn Error>` is allowed, because it allows any `Err` value to be returned early. Even though the body of this `main` function will only ever return errors of type `std::io::Error`, by specifying `Box<dyn Error>`, this signature will continue to be correct even if more code that returns other errors is added to the body of `main`. When a `main` function returns a `Result<(), E>`, the executable will exit with a value of `0` if `main` returns `Ok(())` and will exit with a nonzero value if `main` returns an `Err` value. Executables written in C return integers when they exit: programs that exit successfully return the integer `0`, and programs that error return some integer other than `0`. Rust also returns integers from executables to be compatible with this convention. The `main` function may return any types that implement [the `std::process::Termination` trait](../std/process/trait.termination), which contains a function `report` that returns an `ExitCode`. Consult the standard library documentation for more information on implementing the `Termination` trait for your own types. Now that we’ve discussed the details of calling `panic!` or returning `Result`, let’s return to the topic of how to decide which is appropriate to use in which cases.
programming_docs
rust All the Places Patterns Can Be Used All the Places Patterns Can Be Used =================================== Patterns pop up in a number of places in Rust, and you’ve been using them a lot without realizing it! This section discusses all the places where patterns are valid. ### `match` Arms As discussed in Chapter 6, we use patterns in the arms of `match` expressions. Formally, `match` expressions are defined as the keyword `match`, a value to match on, and one or more match arms that consist of a pattern and an expression to run if the value matches that arm’s pattern, like this: ``` match VALUE { PATTERN => EXPRESSION, PATTERN => EXPRESSION, PATTERN => EXPRESSION, } ``` For example, here's the `match` expression from Listing 6-5 that matches on an `Option<i32>` value in the variable `x`: ``` match x { None => None, Some(i) => Some(i + 1), } ``` The patterns in this `match` expression are the `None` and `Some(i)` on the left of each arrow. One requirement for `match` expressions is that they need to be *exhaustive* in the sense that all possibilities for the value in the `match` expression must be accounted for. One way to ensure you’ve covered every possibility is to have a catchall pattern for the last arm: for example, a variable name matching any value can never fail and thus covers every remaining case. The particular pattern `_` will match anything, but it never binds to a variable, so it’s often used in the last match arm. The `_` pattern can be useful when you want to ignore any value not specified, for example. We’ll cover the `_` pattern in more detail in the [“Ignoring Values in a Pattern”](ch18-03-pattern-syntax#ignoring-values-in-a-pattern) section later in this chapter. ### Conditional `if let` Expressions In Chapter 6 we discussed how to use `if let` expressions mainly as a shorter way to write the equivalent of a `match` that only matches one case. Optionally, `if let` can have a corresponding `else` containing code to run if the pattern in the `if let` doesn’t match. Listing 18-1 shows that it’s also possible to mix and match `if let`, `else if`, and `else if let` expressions. Doing so gives us more flexibility than a `match` expression in which we can express only one value to compare with the patterns. Also, Rust doesn't require that the conditions in a series of `if let`, `else if`, `else if let` arms relate to each other. The code in Listing 18-1 determines what color to make your background based on a series of checks for several conditions. For this example, we’ve created variables with hardcoded values that a real program might receive from user input. Filename: src/main.rs ``` fn main() { let favorite_color: Option<&str> = None; let is_tuesday = false; let age: Result<u8, _> = "34".parse(); if let Some(color) = favorite_color { println!("Using your favorite color, {color}, as the background"); } else if is_tuesday { println!("Tuesday is green day!"); } else if let Ok(age) = age { if age > 30 { println!("Using purple as the background color"); } else { println!("Using orange as the background color"); } } else { println!("Using blue as the background color"); } } ``` Listing 18-1: Mixing `if let`, `else if`, `else if let`, and `else` If the user specifies a favorite color, that color is used as the background. If no favorite color is specified and today is Tuesday, the background color is green. Otherwise, if the user specifies their age as a string and we can parse it as a number successfully, the color is either purple or orange depending on the value of the number. If none of these conditions apply, the background color is blue. This conditional structure lets us support complex requirements. With the hardcoded values we have here, this example will print `Using purple as the background color`. You can see that `if let` can also introduce shadowed variables in the same way that `match` arms can: the line `if let Ok(age) = age` introduces a new shadowed `age` variable that contains the value inside the `Ok` variant. This means we need to place the `if age > 30` condition within that block: we can’t combine these two conditions into `if let Ok(age) = age && age > 30`. The shadowed `age` we want to compare to 30 isn’t valid until the new scope starts with the curly bracket. The downside of using `if let` expressions is that the compiler doesn’t check for exhaustiveness, whereas with `match` expressions it does. If we omitted the last `else` block and therefore missed handling some cases, the compiler would not alert us to the possible logic bug. ### `while let` Conditional Loops Similar in construction to `if let`, the `while let` conditional loop allows a `while` loop to run for as long as a pattern continues to match. In Listing 18-2 we code a `while let` loop that uses a vector as a stack and prints the values in the vector in the opposite order in which they were pushed. ``` fn main() { let mut stack = Vec::new(); stack.push(1); stack.push(2); stack.push(3); while let Some(top) = stack.pop() { println!("{}", top); } } ``` Listing 18-2: Using a `while let` loop to print values for as long as `stack.pop()` returns `Some` This example prints 3, 2, and then 1. The `pop` method takes the last element out of the vector and returns `Some(value)`. If the vector is empty, `pop` returns `None`. The `while` loop continues running the code in its block as long as `pop` returns `Some`. When `pop` returns `None`, the loop stops. We can use `while let` to pop every element off our stack. ### `for` Loops In a `for` loop, the value that directly follows the keyword `for` is a pattern. For example, in `for x in y` the `x` is the pattern. Listing 18-3 demonstrates how to use a pattern in a `for` loop to destructure, or break apart, a tuple as part of the `for` loop. ``` fn main() { let v = vec!['a', 'b', 'c']; for (index, value) in v.iter().enumerate() { println!("{} is at index {}", value, index); } } ``` Listing 18-3: Using a pattern in a `for` loop to destructure a tuple The code in Listing 18-3 will print the following: ``` $ cargo run Compiling patterns v0.1.0 (file:///projects/patterns) Finished dev [unoptimized + debuginfo] target(s) in 0.52s Running `target/debug/patterns` a is at index 0 b is at index 1 c is at index 2 ``` We adapt an iterator using the `enumerate` method so it produces a value and the index for that value, placed into a tuple. The first value produced is the tuple `(0, 'a')`. When this value is matched to the pattern `(index, value)`, `index` will be `0` and `value` will be `'a'`, printing the first line of the output. ### `let` Statements Prior to this chapter, we had only explicitly discussed using patterns with `match` and `if let`, but in fact, we’ve used patterns in other places as well, including in `let` statements. For example, consider this straightforward variable assignment with `let`: ``` #![allow(unused)] fn main() { let x = 5; } ``` Every time you've used a `let` statement like this you've been using patterns, although you might not have realized it! More formally, a `let` statement looks like this: ``` let PATTERN = EXPRESSION; ``` In statements like `let x = 5;` with a variable name in the `PATTERN` slot, the variable name is just a particularly simple form of a pattern. Rust compares the expression against the pattern and assigns any names it finds. So in the `let x = 5;` example, `x` is a pattern that means “bind what matches here to the variable `x`.” Because the name `x` is the whole pattern, this pattern effectively means “bind everything to the variable `x`, whatever the value is.” To see the pattern matching aspect of `let` more clearly, consider Listing 18-4, which uses a pattern with `let` to destructure a tuple. ``` fn main() { let (x, y, z) = (1, 2, 3); } ``` Listing 18-4: Using a pattern to destructure a tuple and create three variables at once Here, we match a tuple against a pattern. Rust compares the value `(1, 2, 3)` to the pattern `(x, y, z)` and sees that the value matches the pattern, so Rust binds `1` to `x`, `2` to `y`, and `3` to `z`. You can think of this tuple pattern as nesting three individual variable patterns inside it. If the number of elements in the pattern doesn’t match the number of elements in the tuple, the overall type won’t match and we’ll get a compiler error. For example, Listing 18-5 shows an attempt to destructure a tuple with three elements into two variables, which won’t work. ``` fn main() { let (x, y) = (1, 2, 3); } ``` Listing 18-5: Incorrectly constructing a pattern whose variables don’t match the number of elements in the tuple Attempting to compile this code results in this type error: ``` $ cargo run Compiling patterns v0.1.0 (file:///projects/patterns) error[E0308]: mismatched types --> src/main.rs:2:9 | 2 | let (x, y) = (1, 2, 3); | ^^^^^^ --------- this expression has type `({integer}, {integer}, {integer})` | | | expected a tuple with 3 elements, found one with 2 elements | = note: expected tuple `({integer}, {integer}, {integer})` found tuple `(_, _)` For more information about this error, try `rustc --explain E0308`. error: could not compile `patterns` due to previous error ``` To fix the error, we could ignore one or more of the values in the tuple using `_` or `..`, as you’ll see in the [“Ignoring Values in a Pattern”](ch18-03-pattern-syntax#ignoring-values-in-a-pattern) section. If the problem is that we have too many variables in the pattern, the solution is to make the types match by removing variables so the number of variables equals the number of elements in the tuple. ### Function Parameters Function parameters can also be patterns. The code in Listing 18-6, which declares a function named `foo` that takes one parameter named `x` of type `i32`, should by now look familiar. ``` fn foo(x: i32) { // code goes here } fn main() {} ``` Listing 18-6: A function signature uses patterns in the parameters The `x` part is a pattern! As we did with `let`, we could match a tuple in a function’s arguments to the pattern. Listing 18-7 splits the values in a tuple as we pass it to a function. Filename: src/main.rs ``` fn print_coordinates(&(x, y): &(i32, i32)) { println!("Current location: ({}, {})", x, y); } fn main() { let point = (3, 5); print_coordinates(&point); } ``` Listing 18-7: A function with parameters that destructure a tuple This code prints `Current location: (3, 5)`. The values `&(3, 5)` match the pattern `&(x, y)`, so `x` is the value `3` and `y` is the value `5`. We can also use patterns in closure parameter lists in the same way as in function parameter lists, because closures are similar to functions, as discussed in Chapter 13. At this point, you’ve seen several ways of using patterns, but patterns don’t work the same in every place we can use them. In some places, the patterns must be irrefutable; in other circumstances, they can be refutable. We’ll discuss these two concepts next. rust Appendix E - Editions Appendix E - Editions ===================== In Chapter 1, you saw that `cargo new` adds a bit of metadata to your *Cargo.toml* file about an edition. This appendix talks about what that means! The Rust language and compiler have a six-week release cycle, meaning users get a constant stream of new features. Other programming languages release larger changes less often; Rust releases smaller updates more frequently. After a while, all of these tiny changes add up. But from release to release, it can be difficult to look back and say, “Wow, between Rust 1.10 and Rust 1.31, Rust has changed a lot!” Every two or three years, the Rust team produces a new Rust *edition*. Each edition brings together the features that have landed into a clear package with fully updated documentation and tooling. New editions ship as part of the usual six-week release process. Editions serve different purposes for different people: * For active Rust users, a new edition brings together incremental changes into an easy-to-understand package. * For non-users, a new edition signals that some major advancements have landed, which might make Rust worth another look. * For those developing Rust, a new edition provides a rallying point for the project as a whole. At the time of this writing, three Rust editions are available: Rust 2015, Rust 2018, and Rust 2021. This book is written using Rust 2021 edition idioms. The `edition` key in *Cargo.toml* indicates which edition the compiler should use for your code. If the key doesn’t exist, Rust uses `2015` as the edition value for backward compatibility reasons. Each project can opt in to an edition other than the default 2015 edition. Editions can contain incompatible changes, such as including a new keyword that conflicts with identifiers in code. However, unless you opt in to those changes, your code will continue to compile even as you upgrade the Rust compiler version you use. All Rust compiler versions support any edition that existed prior to that compiler’s release, and they can link crates of any supported editions together. Edition changes only affect the way the compiler initially parses code. Therefore, if you’re using Rust 2015 and one of your dependencies uses Rust 2018, your project will compile and be able to use that dependency. The opposite situation, where your project uses Rust 2018 and a dependency uses Rust 2015, works as well. To be clear: most features will be available on all editions. Developers using any Rust edition will continue to see improvements as new stable releases are made. However, in some cases, mainly when new keywords are added, some new features might only be available in later editions. You will need to switch editions if you want to take advantage of such features. For more details, the [*Edition Guide*](https://doc.rust-lang.org/stable/edition-guide/index.html) is a complete book about editions that enumerates the differences between editions and explains how to automatically upgrade your code to a new edition via `cargo fix`. rust Building a Single-Threaded Web Server Building a Single-Threaded Web Server ===================================== We’ll start by getting a single-threaded web server working. Before we begin, let’s look at a quick overview of the protocols involved in building web servers. The details of these protocols are beyond the scope of this book, but a brief overview will give you the information you need. The two main protocols involved in web servers are *Hypertext Transfer Protocol* *(HTTP)* and *Transmission Control Protocol* *(TCP)*. Both protocols are *request-response* protocols, meaning a *client* initiates requests and a *server* listens to the requests and provides a response to the client. The contents of those requests and responses are defined by the protocols. TCP is the lower-level protocol that describes the details of how information gets from one server to another but doesn’t specify what that information is. HTTP builds on top of TCP by defining the contents of the requests and responses. It’s technically possible to use HTTP with other protocols, but in the vast majority of cases, HTTP sends its data over TCP. We’ll work with the raw bytes of TCP and HTTP requests and responses. ### Listening to the TCP Connection Our web server needs to listen to a TCP connection, so that’s the first part we’ll work on. The standard library offers a `std::net` module that lets us do this. Let’s make a new project in the usual fashion: ``` $ cargo new hello Created binary (application) `hello` project $ cd hello ``` Now enter the code in Listing 20-1 in *src/main.rs* to start. This code will listen at the local address `127.0.0.1:7878` for incoming TCP streams. When it gets an incoming stream, it will print `Connection established!`. Filename: src/main.rs ``` use std::net::TcpListener; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); println!("Connection established!"); } } ``` Listing 20-1: Listening for incoming streams and printing a message when we receive a stream Using `TcpListener`, we can listen for TCP connections at the address `127.0.0.1:7878`. In the address, the section before the colon is an IP address representing your computer (this is the same on every computer and doesn’t represent the authors’ computer specifically), and `7878` is the port. We’ve chosen this port for two reasons: HTTP isn’t normally accepted on this port so our server is unlikely to conflict with any other web server you might have running on your machine, and 7878 is *rust* typed on a telephone. The `bind` function in this scenario works like the `new` function in that it will return a new `TcpListener` instance. The function is called `bind` because, in networking, connecting to a port to listen to is known as “binding to a port.” The `bind` function returns a `Result<T, E>`, which indicates that it’s possible for binding to fail. For example, connecting to port 80 requires administrator privileges (nonadministrators can listen only on ports higher than 1023), so if we tried to connect to port 80 without being an administrator, binding wouldn’t work. Binding also wouldn’t work, for example, if we ran two instances of our program and so had two programs listening to the same port. Because we’re writing a basic server just for learning purposes, we won’t worry about handling these kinds of errors; instead, we use `unwrap` to stop the program if errors happen. The `incoming` method on `TcpListener` returns an iterator that gives us a sequence of streams (more specifically, streams of type `TcpStream`). A single *stream* represents an open connection between the client and the server. A *connection* is the name for the full request and response process in which a client connects to the server, the server generates a response, and the server closes the connection. As such, we will read from the `TcpStream` to see what the client sent and then write our response to the stream to send data back to the client. Overall, this `for` loop will process each connection in turn and produce a series of streams for us to handle. For now, our handling of the stream consists of calling `unwrap` to terminate our program if the stream has any errors; if there aren’t any errors, the program prints a message. We’ll add more functionality for the success case in the next listing. The reason we might receive errors from the `incoming` method when a client connects to the server is that we’re not actually iterating over connections. Instead, we’re iterating over *connection attempts*. The connection might not be successful for a number of reasons, many of them operating system specific. For example, many operating systems have a limit to the number of simultaneous open connections they can support; new connection attempts beyond that number will produce an error until some of the open connections are closed. Let’s try running this code! Invoke `cargo run` in the terminal and then load *127.0.0.1:7878* in a web browser. The browser should show an error message like “Connection reset,” because the server isn’t currently sending back any data. But when you look at your terminal, you should see several messages that were printed when the browser connected to the server! ``` Running `target/debug/hello` Connection established! Connection established! Connection established! ``` Sometimes, you’ll see multiple messages printed for one browser request; the reason might be that the browser is making a request for the page as well as a request for other resources, like the *favicon.ico* icon that appears in the browser tab. It could also be that the browser is trying to connect to the server multiple times because the server isn’t responding with any data. When `stream` goes out of scope and is dropped at the end of the loop, the connection is closed as part of the `drop` implementation. Browsers sometimes deal with closed connections by retrying, because the problem might be temporary. The important factor is that we’ve successfully gotten a handle to a TCP connection! Remember to stop the program by pressing ctrl-c when you’re done running a particular version of the code. Then restart the program by invoking the `cargo run` command after you’ve made each set of code changes to make sure you’re running the newest code. ### Reading the Request Let’s implement the functionality to read the request from the browser! To separate the concerns of first getting a connection and then taking some action with the connection, we’ll start a new function for processing connections. In this new `handle_connection` function, we’ll read data from the TCP stream and print it so we can see the data being sent from the browser. Change the code to look like Listing 20-2. Filename: src/main.rs ``` use std::{ io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, }; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let http_request: Vec<_> = buf_reader .lines() .map(|result| result.unwrap()) .take_while(|line| !line.is_empty()) .collect(); println!("Request: {:#?}", http_request); } ``` Listing 20-2: Reading from the `TcpStream` and printing the data We bring `std::io::prelude` and `std::io::BufReader` into scope to get access to traits and types that let us read from and write to the stream. In the `for` loop in the `main` function, instead of printing a message that says we made a connection, we now call the new `handle_connection` function and pass the `stream` to it. In the `handle_connection` function, we create a new `BufReader` instance that wraps a mutable reference to the `stream`. `BufReader` adds buffering by managing calls to the `std::io::Read` trait methods for us. We create a variable named `http_request` to collect the lines of the request the browser sends to our server. We indicate that we want to collect these lines in a vector by adding the `Vec<_>` type annotation. `BufReader` implements the `std::io::BufRead` trait, which provides the `lines` method. The `lines` method returns an iterator of `Result<String, std::io::Error>` by splitting the stream of data whenever it sees a newline byte. To get each `String`, we map and `unwrap` each `Result`. The `Result` might be an error if the data isn’t valid UTF-8 or if there was a problem reading from the stream. Again, a production program should handle these errors more gracefully, but we’re choosing to stop the program in the error case for simplicity. The browser signals the end of an HTTP request by sending two newline characters in a row, so to get one request from the stream, we take lines until we get a line that is the empty string. Once we’ve collected the lines into the vector, we’re printing them out using pretty debug formatting so we can take a look at the instructions the web browser is sending to our server. Let’s try this code! Start the program and make a request in a web browser again. Note that we’ll still get an error page in the browser, but our program’s output in the terminal will now look similar to this: ``` $ cargo run Compiling hello v0.1.0 (file:///projects/hello) Finished dev [unoptimized + debuginfo] target(s) in 0.42s Running `target/debug/hello` Request: [ "GET / HTTP/1.1", "Host: 127.0.0.1:7878", "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:99.0) Gecko/20100101 Firefox/99.0", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", "Accept-Language: en-US,en;q=0.5", "Accept-Encoding: gzip, deflate, br", "DNT: 1", "Connection: keep-alive", "Upgrade-Insecure-Requests: 1", "Sec-Fetch-Dest: document", "Sec-Fetch-Mode: navigate", "Sec-Fetch-Site: none", "Sec-Fetch-User: ?1", "Cache-Control: max-age=0", ] ``` Depending on your browser, you might get slightly different output. Now that we’re printing the request data, we can see why we get multiple connections from one browser request by looking at the path after `GET` in the first line of the request. If the repeated connections are all requesting */*, we know the browser is trying to fetch */* repeatedly because it’s not getting a response from our program. Let’s break down this request data to understand what the browser is asking of our program. ### A Closer Look at an HTTP Request HTTP is a text-based protocol, and a request takes this format: ``` Method Request-URI HTTP-Version CRLF headers CRLF message-body ``` The first line is the *request line* that holds information about what the client is requesting. The first part of the request line indicates the *method* being used, such as `GET` or `POST`, which describes how the client is making this request. Our client used a `GET` request, which means it is asking for information. The next part of the request line is */*, which indicates the *Uniform Resource Identifier* *(URI)* the client is requesting: a URI is almost, but not quite, the same as a *Uniform Resource Locator* *(URL)*. The difference between URIs and URLs isn’t important for our purposes in this chapter, but the HTTP spec uses the term URI, so we can just mentally substitute URL for URI here. The last part is the HTTP version the client uses, and then the request line ends in a *CRLF sequence*. (CRLF stands for *carriage return* and *line feed*, which are terms from the typewriter days!) The CRLF sequence can also be written as `\r\n`, where `\r` is a carriage return and `\n` is a line feed. The CRLF sequence separates the request line from the rest of the request data. Note that when the CRLF is printed, we see a new line start rather than `\r\n`. Looking at the request line data we received from running our program so far, we see that `GET` is the method, */* is the request URI, and `HTTP/1.1` is the version. After the request line, the remaining lines starting from `Host:` onward are headers. `GET` requests have no body. Try making a request from a different browser or asking for a different address, such as *127.0.0.1:7878/test*, to see how the request data changes. Now that we know what the browser is asking for, let’s send back some data! ### Writing a Response We’re going to implement sending data in response to a client request. Responses have the following format: ``` HTTP-Version Status-Code Reason-Phrase CRLF headers CRLF message-body ``` The first line is a *status line* that contains the HTTP version used in the response, a numeric status code that summarizes the result of the request, and a reason phrase that provides a text description of the status code. After the CRLF sequence are any headers, another CRLF sequence, and the body of the response. Here is an example response that uses HTTP version 1.1, has a status code of 200, an OK reason phrase, no headers, and no body: ``` HTTP/1.1 200 OK\r\n\r\n ``` The status code 200 is the standard success response. The text is a tiny successful HTTP response. Let’s write this to the stream as our response to a successful request! From the `handle_connection` function, remove the `println!` that was printing the request data and replace it with the code in Listing 20-3. Filename: src/main.rs ``` use std::{ io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, }; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let http_request: Vec<_> = buf_reader .lines() .map(|result| result.unwrap()) .take_while(|line| !line.is_empty()) .collect(); let response = "HTTP/1.1 200 OK\r\n\r\n"; stream.write_all(response.as_bytes()).unwrap(); } ``` Listing 20-3: Writing a tiny successful HTTP response to the stream The first new line defines the `response` variable that holds the success message’s data. Then we call `as_bytes` on our `response` to convert the string data to bytes. The `write_all` method on `stream` takes a `&[u8]` and sends those bytes directly down the connection. Because the `write_all` operation could fail, we use `unwrap` on any error result as before. Again, in a real application you would add error handling here. With these changes, let’s run our code and make a request. We’re no longer printing any data to the terminal, so we won’t see any output other than the output from Cargo. When you load *127.0.0.1:7878* in a web browser, you should get a blank page instead of an error. You’ve just hand-coded receiving an HTTP request and sending a response! ### Returning Real HTML Let’s implement the functionality for returning more than a blank page. Create the new file *hello.html* in the root of your project directory, not in the *src* directory. You can input any HTML you want; Listing 20-4 shows one possibility. Filename: hello.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Hello!</title> </head> <body> <h1>Hello!</h1> <p>Hi from Rust</p> </body> </html> ``` Listing 20-4: A sample HTML file to return in a response This is a minimal HTML5 document with a heading and some text. To return this from the server when a request is received, we’ll modify `handle_connection` as shown in Listing 20-5 to read the HTML file, add it to the response as a body, and send it. Filename: src/main.rs ``` use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, }; // --snip-- fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let http_request: Vec<_> = buf_reader .lines() .map(|result| result.unwrap()) .take_while(|line| !line.is_empty()) .collect(); let status_line = "HTTP/1.1 200 OK"; let contents = fs::read_to_string("hello.html").unwrap(); let length = contents.len(); let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"); stream.write_all(response.as_bytes()).unwrap(); } ``` Listing 20-5: Sending the contents of *hello.html* as the body of the response We’ve added `fs` to the `use` statement to bring the standard library’s filesystem module into scope. The code for reading the contents of a file to a string should look familiar; we used it in Chapter 12 when we read the contents of a file for our I/O project in Listing 12-4. Next, we use `format!` to add the file’s contents as the body of the success response. To ensure a valid HTTP response, we add the `Content-Length` header which is set to the size of our response body, in this case the size of `hello.html`. Run this code with `cargo run` and load *127.0.0.1:7878* in your browser; you should see your HTML rendered! Currently, we’re ignoring the request data in `http_request` and just sending back the contents of the HTML file unconditionally. That means if you try requesting *127.0.0.1:7878/something-else* in your browser, you’ll still get back this same HTML response. At the moment, our server is very limited and does not do what most web servers do. We want to customize our responses depending on the request and only send back the HTML file for a well-formed request to */*. ### Validating the Request and Selectively Responding Right now, our web server will return the HTML in the file no matter what the client requested. Let’s add functionality to check that the browser is requesting */* before returning the HTML file and return an error if the browser requests anything else. For this we need to modify `handle_connection`, as shown in Listing 20-6. This new code checks the content of the request received against what we know a request for */* looks like and adds `if` and `else` blocks to treat requests differently. Filename: src/main.rs ``` use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, }; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } // --snip-- fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let request_line = buf_reader.lines().next().unwrap().unwrap(); if request_line == "GET / HTTP/1.1" { let status_line = "HTTP/1.1 200 OK"; let contents = fs::read_to_string("hello.html").unwrap(); let length = contents.len(); let response = format!( "{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}" ); stream.write_all(response.as_bytes()).unwrap(); } else { // some other request } } ``` Listing 20-6: Handling requests to */* differently from other requests We’re only going to be looking at the first line of the HTTP request, so rather than reading the entire request into a vector, we’re calling `next` to get the first item from the iterator. The first `unwrap` takes care of the `Option` and stops the program if the iterator has no items. The second `unwrap` handles the `Result` and has the same effect as the `unwrap` that was in the `map` added in Listing 20-2. Next, we check the `request_line` to see if it equals the request line of a GET request to the */* path. If it does, the `if` block returns the contents of our HTML file. If the `request_line` does *not* equal the GET request to the */* path, it means we’ve received some other request. We’ll add code to the `else` block in a moment to respond to all other requests. Run this code now and request *127.0.0.1:7878*; you should get the HTML in *hello.html*. If you make any other request, such as *127.0.0.1:7878/something-else*, you’ll get a connection error like those you saw when running the code in Listing 20-1 and Listing 20-2. Now let’s add the code in Listing 20-7 to the `else` block to return a response with the status code 404, which signals that the content for the request was not found. We’ll also return some HTML for a page to render in the browser indicating the response to the end user. Filename: src/main.rs ``` use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, }; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let request_line = buf_reader.lines().next().unwrap().unwrap(); if request_line == "GET / HTTP/1.1" { let status_line = "HTTP/1.1 200 OK"; let contents = fs::read_to_string("hello.html").unwrap(); let length = contents.len(); let response = format!( "{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}" ); stream.write_all(response.as_bytes()).unwrap(); // --snip-- } else { let status_line = "HTTP/1.1 404 NOT FOUND"; let contents = fs::read_to_string("404.html").unwrap(); let length = contents.len(); let response = format!( "{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}" ); stream.write_all(response.as_bytes()).unwrap(); } } ``` Listing 20-7: Responding with status code 404 and an error page if anything other than */* was requested Here, our response has a status line with status code 404 and the reason phrase `NOT FOUND`. The body of the response will be the HTML in the file *404.html*. You’ll need to create a *404.html* file next to *hello.html* for the error page; again feel free to use any HTML you want or use the example HTML in Listing 20-8. Filename: 404.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Hello!</title> </head> <body> <h1>Oops!</h1> <p>Sorry, I don't know what you're asking for.</p> </body> </html> ``` Listing 20-8: Sample content for the page to send back with any 404 response With these changes, run your server again. Requesting *127.0.0.1:7878* should return the contents of *hello.html*, and any other request, like *127.0.0.1:7878/foo*, should return the error HTML from *404.html*. ### A Touch of Refactoring At the moment the `if` and `else` blocks have a lot of repetition: they’re both reading files and writing the contents of the files to the stream. The only differences are the status line and the filename. Let’s make the code more concise by pulling out those differences into separate `if` and `else` lines that will assign the values of the status line and the filename to variables; we can then use those variables unconditionally in the code to read the file and write the response. Listing 20-9 shows the resulting code after replacing the large `if` and `else` blocks. Filename: src/main.rs ``` use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, }; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } // --snip-- fn handle_connection(mut stream: TcpStream) { // --snip-- let buf_reader = BufReader::new(&mut stream); let request_line = buf_reader.lines().next().unwrap().unwrap(); let (status_line, filename) = if request_line == "GET / HTTP/1.1" { ("HTTP/1.1 200 OK", "hello.html") } else { ("HTTP/1.1 404 NOT FOUND", "404.html") }; let contents = fs::read_to_string(filename).unwrap(); let length = contents.len(); let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"); stream.write_all(response.as_bytes()).unwrap(); } ``` Listing 20-9: Refactoring the `if` and `else` blocks to contain only the code that differs between the two cases Now the `if` and `else` blocks only return the appropriate values for the status line and filename in a tuple; we then use destructuring to assign these two values to `status_line` and `filename` using a pattern in the `let` statement, as discussed in Chapter 18. The previously duplicated code is now outside the `if` and `else` blocks and uses the `status_line` and `filename` variables. This makes it easier to see the difference between the two cases, and it means we have only one place to update the code if we want to change how the file reading and response writing work. The behavior of the code in Listing 20-9 will be the same as that in Listing 20-8. Awesome! We now have a simple web server in approximately 40 lines of Rust code that responds to one request with a page of content and responds to all other requests with a 404 response. Currently, our server runs in a single thread, meaning it can only serve one request at a time. Let’s examine how that can be a problem by simulating some slow requests. Then we’ll fix it so our server can handle multiple requests at once.
programming_docs
rust Working with Environment Variables Working with Environment Variables ================================== We’ll improve `minigrep` by adding an extra feature: an option for case-insensitive searching that the user can turn on via an environment variable. We could make this feature a command line option and require that users enter it each time they want it to apply, but by instead making it an environment variable, we allow our users to set the environment variable once and have all their searches be case insensitive in that terminal session. ### Writing a Failing Test for the Case-Insensitive `search` Function We first add a new `search_case_insensitive` function that will be called when the environment variable has a value. We’ll continue to follow the TDD process, so the first step is again to write a failing test. We’ll add a new test for the new `search_case_insensitive` function and rename our old test from `one_result` to `case_sensitive` to clarify the differences between the two tests, as shown in Listing 12-20. Filename: src/lib.rs ``` use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, } impl Config { pub fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; for line in search(&config.query, &contents) { println!("{line}"); } Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(query) { results.push(line); } } results } #[cfg(test)] mod tests { use super::*; #[test] fn case_sensitive() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three. Duct tape."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } #[test] fn case_insensitive() { let query = "rUsT"; let contents = "\ Rust: safe, fast, productive. Pick three. Trust me."; assert_eq!( vec!["Rust:", "Trust me."], search_case_insensitive(query, contents) ); } } ``` Listing 12-20: Adding a new failing test for the case-insensitive function we’re about to add Note that we’ve edited the old test’s `contents` too. We’ve added a new line with the text `"Duct tape."` using a capital D that shouldn’t match the query `"duct"` when we’re searching in a case-sensitive manner. Changing the old test in this way helps ensure that we don’t accidentally break the case-sensitive search functionality that we’ve already implemented. This test should pass now and should continue to pass as we work on the case-insensitive search. The new test for the case-*insensitive* search uses `"rUsT"` as its query. In the `search_case_insensitive` function we’re about to add, the query `"rUsT"` should match the line containing `"Rust:"` with a capital R and match the line `"Trust me."` even though both have different casing from the query. This is our failing test, and it will fail to compile because we haven’t yet defined the `search_case_insensitive` function. Feel free to add a skeleton implementation that always returns an empty vector, similar to the way we did for the `search` function in Listing 12-16 to see the test compile and fail. ### Implementing the `search_case_insensitive` Function The `search_case_insensitive` function, shown in Listing 12-21, will be almost the same as the `search` function. The only difference is that we’ll lowercase the `query` and each `line` so whatever the case of the input arguments, they’ll be the same case when we check whether the line contains the query. Filename: src/lib.rs ``` use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, } impl Config { pub fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; for line in search(&config.query, &contents) { println!("{line}"); } Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(query) { results.push(line); } } results } pub fn search_case_insensitive<'a>( query: &str, contents: &'a str, ) -> Vec<&'a str> { let query = query.to_lowercase(); let mut results = Vec::new(); for line in contents.lines() { if line.to_lowercase().contains(&query) { results.push(line); } } results } #[cfg(test)] mod tests { use super::*; #[test] fn case_sensitive() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three. Duct tape."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } #[test] fn case_insensitive() { let query = "rUsT"; let contents = "\ Rust: safe, fast, productive. Pick three. Trust me."; assert_eq!( vec!["Rust:", "Trust me."], search_case_insensitive(query, contents) ); } } ``` Listing 12-21: Defining the `search_case_insensitive` function to lowercase the query and the line before comparing them First, we lowercase the `query` string and store it in a shadowed variable with the same name. Calling `to_lowercase` on the query is necessary so no matter whether the user’s query is `"rust"`, `"RUST"`, `"Rust"`, or `"rUsT"`, we’ll treat the query as if it were `"rust"` and be insensitive to the case. While `to_lowercase` will handle basic Unicode, it won’t be 100% accurate. If we were writing a real application, we’d want to do a bit more work here, but this section is about environment variables, not Unicode, so we’ll leave it at that here. Note that `query` is now a `String` rather than a string slice, because calling `to_lowercase` creates new data rather than referencing existing data. Say the query is `"rUsT"`, as an example: that string slice doesn’t contain a lowercase `u` or `t` for us to use, so we have to allocate a new `String` containing `"rust"`. When we pass `query` as an argument to the `contains` method now, we need to add an ampersand because the signature of `contains` is defined to take a string slice. Next, we add a call to `to_lowercase` on each `line` to lowercase all characters. Now that we’ve converted `line` and `query` to lowercase, we’ll find matches no matter what the case of the query is. Let’s see if this implementation passes the tests: ``` $ cargo test Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished test [unoptimized + debuginfo] target(s) in 1.33s Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94) running 2 tests test tests::case_insensitive ... ok test tests::case_sensitive ... ok test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Running unittests src/main.rs (target/debug/deps/minigrep-9cd200e5fac0fc94) running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests minigrep running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` Great! They passed. Now, let’s call the new `search_case_insensitive` function from the `run` function. First, we’ll add a configuration option to the `Config` struct to switch between case-sensitive and case-insensitive search. Adding this field will cause compiler errors because we aren’t initializing this field anywhere yet: Filename: src/lib.rs ``` use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, pub ignore_case: bool, } impl Config { pub fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; let results = if config.ignore_case { search_case_insensitive(&config.query, &contents) } else { search(&config.query, &contents) }; for line in results { println!("{line}"); } Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(query) { results.push(line); } } results } pub fn search_case_insensitive<'a>( query: &str, contents: &'a str, ) -> Vec<&'a str> { let query = query.to_lowercase(); let mut results = Vec::new(); for line in contents.lines() { if line.to_lowercase().contains(&query) { results.push(line); } } results } #[cfg(test)] mod tests { use super::*; #[test] fn case_sensitive() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three. Duct tape."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } #[test] fn case_insensitive() { let query = "rUsT"; let contents = "\ Rust: safe, fast, productive. Pick three. Trust me."; assert_eq!( vec!["Rust:", "Trust me."], search_case_insensitive(query, contents) ); } } ``` We added the `ignore_case` field that holds a Boolean. Next, we need the `run` function to check the `ignore_case` field’s value and use that to decide whether to call the `search` function or the `search_case_insensitive` function, as shown in Listing 12-22. This still won’t compile yet. Filename: src/lib.rs ``` use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, pub ignore_case: bool, } impl Config { pub fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; let results = if config.ignore_case { search_case_insensitive(&config.query, &contents) } else { search(&config.query, &contents) }; for line in results { println!("{line}"); } Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(query) { results.push(line); } } results } pub fn search_case_insensitive<'a>( query: &str, contents: &'a str, ) -> Vec<&'a str> { let query = query.to_lowercase(); let mut results = Vec::new(); for line in contents.lines() { if line.to_lowercase().contains(&query) { results.push(line); } } results } #[cfg(test)] mod tests { use super::*; #[test] fn case_sensitive() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three. Duct tape."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } #[test] fn case_insensitive() { let query = "rUsT"; let contents = "\ Rust: safe, fast, productive. Pick three. Trust me."; assert_eq!( vec!["Rust:", "Trust me."], search_case_insensitive(query, contents) ); } } ``` Listing 12-22: Calling either `search` or `search_case_insensitive` based on the value in `config.ignore_case` Finally, we need to check for the environment variable. The functions for working with environment variables are in the `env` module in the standard library, so we bring that module into scope at the top of *src/lib.rs*. Then we’ll use the `var` function from the `env` module to check to see if any value has been set for an environment variable named `IGNORE_CASE`, as shown in Listing 12-23. Filename: src/lib.rs ``` use std::env; // --snip-- use std::error::Error; use std::fs; pub struct Config { pub query: String, pub file_path: String, pub ignore_case: bool, } impl Config { pub fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); let ignore_case = env::var("IGNORE_CASE").is_ok(); Ok(Config { query, file_path, ignore_case, }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; let results = if config.ignore_case { search_case_insensitive(&config.query, &contents) } else { search(&config.query, &contents) }; for line in results { println!("{line}"); } Ok(()) } pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(query) { results.push(line); } } results } pub fn search_case_insensitive<'a>( query: &str, contents: &'a str, ) -> Vec<&'a str> { let query = query.to_lowercase(); let mut results = Vec::new(); for line in contents.lines() { if line.to_lowercase().contains(&query) { results.push(line); } } results } #[cfg(test)] mod tests { use super::*; #[test] fn case_sensitive() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three. Duct tape."; assert_eq!(vec!["safe, fast, productive."], search(query, contents)); } #[test] fn case_insensitive() { let query = "rUsT"; let contents = "\ Rust: safe, fast, productive. Pick three. Trust me."; assert_eq!( vec!["Rust:", "Trust me."], search_case_insensitive(query, contents) ); } } ``` Listing 12-23: Checking for any value in an environment variable named `IGNORE_CASE` Here, we create a new variable `ignore_case`. To set its value, we call the `env::var` function and pass it the name of the `IGNORE_CASE` environment variable. The `env::var` function returns a `Result` that will be the successful `Ok` variant that contains the value of the environment variable if the environment variable is set to any value. It will return the `Err` variant if the environment variable is not set. We’re using the `is_ok` method on the `Result` to check whether the environment variable is set, which means the program should do a case-insensitive search. If the `IGNORE_CASE` environment variable isn’t set to anything, `is_ok` will return false and the program will perform a case-sensitive search. We don’t care about the *value* of the environment variable, just whether it’s set or unset, so we’re checking `is_ok` rather than using `unwrap`, `expect`, or any of the other methods we’ve seen on `Result`. We pass the value in the `ignore_case` variable to the `Config` instance so the `run` function can read that value and decide whether to call `search_case_insensitive` or `search`, as we implemented in Listing 12-22. Let’s give it a try! First, we’ll run our program without the environment variable set and with the query `to`, which should match any line that contains the word “to” in all lowercase: ``` $ cargo run -- to poem.txt Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished dev [unoptimized + debuginfo] target(s) in 0.0s Running `target/debug/minigrep to poem.txt` Are you nobody, too? How dreary to be somebody! ``` Looks like that still works! Now, let’s run the program with `IGNORE_CASE` set to `1` but with the same query `to`. ``` $ IGNORE_CASE=1 cargo run -- to poem.txt ``` If you’re using PowerShell, you will need to set the environment variable and run the program as separate commands: ``` PS> $Env:IGNORE_CASE=1; cargo run -- to poem.txt ``` This will make `IGNORE_CASE` persist for the remainder of your shell session. It can be unset with the `Remove-Item` cmdlet: ``` PS> Remove-Item Env:IGNORE_CASE ``` We should get lines that contain “to” that might have uppercase letters: ``` Are you nobody, too? How dreary to be somebody! To tell your name the livelong day To an admiring bog! ``` Excellent, we also got lines containing “To”! Our `minigrep` program can now do case-insensitive searching controlled by an environment variable. Now you know how to manage options set using either command line arguments or environment variables. Some programs allow arguments *and* environment variables for the same configuration. In those cases, the programs decide that one or the other takes precedence. For another exercise on your own, try controlling case sensitivity through either a command line argument or an environment variable. Decide whether the command line argument or the environment variable should take precedence if the program is run with one set to case sensitive and one set to ignore case. The `std::env` module contains many more useful features for dealing with environment variables: check out its documentation to see what is available. rust Common Collections Common Collections ================== Rust’s standard library includes a number of very useful data structures called *collections*. Most other data types represent one specific value, but collections can contain multiple values. Unlike the built-in array and tuple types, the data these collections point to is stored on the heap, which means the amount of data does not need to be known at compile time and can grow or shrink as the program runs. Each kind of collection has different capabilities and costs, and choosing an appropriate one for your current situation is a skill you’ll develop over time. In this chapter, we’ll discuss three collections that are used very often in Rust programs: * A *vector* allows you to store a variable number of values next to each other. * A *string* is a collection of characters. We’ve mentioned the `String` type previously, but in this chapter we’ll talk about it in depth. * A *hash map* allows you to associate a value with a particular key. It’s a particular implementation of the more general data structure called a *map*. To learn about the other kinds of collections provided by the standard library, see [the documentation](../std/collections/index). We’ll discuss how to create and update vectors, strings, and hash maps, as well as what makes each special. rust Implementing an Object-Oriented Design Pattern Implementing an Object-Oriented Design Pattern ============================================== The *state pattern* is an object-oriented design pattern. The crux of the pattern is that we define a set of states a value can have internally. The states are represented by a set of *state objects*, and the value’s behavior changes based on its state. We’re going to work through an example of a blog post struct that has a field to hold its state, which will be a state object from the set "draft", "review", or "published". The state objects share functionality: in Rust, of course, we use structs and traits rather than objects and inheritance. Each state object is responsible for its own behavior and for governing when it should change into another state. The value that holds a state object knows nothing about the different behavior of the states or when to transition between states. The advantage of using the state pattern is that, when the business requirements of the program change, we won’t need to change the code of the value holding the state or the code that uses the value. We’ll only need to update the code inside one of the state objects to change its rules or perhaps add more state objects. First, we’re going to implement the state pattern in a more traditional object-oriented way, then we’ll use an approach that’s a bit more natural in Rust. Let’s dig in to incrementally implementing a blog post workflow using the state pattern. The final functionality will look like this: 1. A blog post starts as an empty draft. 2. When the draft is done, a review of the post is requested. 3. When the post is approved, it gets published. 4. Only published blog posts return content to print, so unapproved posts can’t accidentally be published. Any other changes attempted on a post should have no effect. For example, if we try to approve a draft blog post before we’ve requested a review, the post should remain an unpublished draft. Listing 17-11 shows this workflow in code form: this is an example usage of the API we’ll implement in a library crate named `blog`. This won’t compile yet because we haven’t implemented the `blog` crate. Filename: src/main.rs ``` use blog::Post; fn main() { let mut post = Post::new(); post.add_text("I ate a salad for lunch today"); assert_eq!("", post.content()); post.request_review(); assert_eq!("", post.content()); post.approve(); assert_eq!("I ate a salad for lunch today", post.content()); } ``` Listing 17-11: Code that demonstrates the desired behavior we want our `blog` crate to have We want to allow the user to create a new draft blog post with `Post::new`. We want to allow text to be added to the blog post. If we try to get the post’s content immediately, before approval, we shouldn’t get any text because the post is still a draft. We’ve added `assert_eq!` in the code for demonstration purposes. An excellent unit test for this would be to assert that a draft blog post returns an empty string from the `content` method, but we’re not going to write tests for this example. Next, we want to enable a request for a review of the post, and we want `content` to return an empty string while waiting for the review. When the post receives approval, it should get published, meaning the text of the post will be returned when `content` is called. Notice that the only type we’re interacting with from the crate is the `Post` type. This type will use the state pattern and will hold a value that will be one of three state objects representing the various states a post can be in—draft, waiting for review, or published. Changing from one state to another will be managed internally within the `Post` type. The states change in response to the methods called by our library’s users on the `Post` instance, but they don’t have to manage the state changes directly. Also, users can’t make a mistake with the states, like publishing a post before it’s reviewed. ### Defining `Post` and Creating a New Instance in the Draft State Let’s get started on the implementation of the library! We know we need a public `Post` struct that holds some content, so we’ll start with the definition of the struct and an associated public `new` function to create an instance of `Post`, as shown in Listing 17-12. We’ll also make a private `State` trait that will define the behavior that all state objects for a `Post` must have. Then `Post` will hold a trait object of `Box<dyn State>` inside an `Option<T>` in a private field named `state` to hold the state object. You’ll see why the `Option<T>` is necessary in a bit. Filename: src/lib.rs ``` pub struct Post { state: Option<Box<dyn State>>, content: String, } impl Post { pub fn new() -> Post { Post { state: Some(Box::new(Draft {})), content: String::new(), } } } trait State {} struct Draft {} impl State for Draft {} ``` Listing 17-12: Definition of a `Post` struct and a `new` function that creates a new `Post` instance, a `State` trait, and a `Draft` struct The `State` trait defines the behavior shared by different post states. The state objects are `Draft`, `PendingReview`, and `Published`, and they will all implement the `State` trait. For now, the trait doesn’t have any methods, and we’ll start by defining just the `Draft` state because that is the state we want a post to start in. When we create a new `Post`, we set its `state` field to a `Some` value that holds a `Box`. This `Box` points to a new instance of the `Draft` struct. This ensures whenever we create a new instance of `Post`, it will start out as a draft. Because the `state` field of `Post` is private, there is no way to create a `Post` in any other state! In the `Post::new` function, we set the `content` field to a new, empty `String`. ### Storing the Text of the Post Content We saw in Listing 17-11 that we want to be able to call a method named `add_text` and pass it a `&str` that is then added as the text content of the blog post. We implement this as a method, rather than exposing the `content` field as `pub`, so that later we can implement a method that will control how the `content` field’s data is read. The `add_text` method is pretty straightforward, so let’s add the implementation in Listing 17-13 to the `impl Post` block: Filename: src/lib.rs ``` pub struct Post { state: Option<Box<dyn State>>, content: String, } impl Post { // --snip-- pub fn new() -> Post { Post { state: Some(Box::new(Draft {})), content: String::new(), } } pub fn add_text(&mut self, text: &str) { self.content.push_str(text); } } trait State {} struct Draft {} impl State for Draft {} ``` Listing 17-13: Implementing the `add_text` method to add text to a post’s `content` The `add_text` method takes a mutable reference to `self`, because we’re changing the `Post` instance that we’re calling `add_text` on. We then call `push_str` on the `String` in `content` and pass the `text` argument to add to the saved `content`. This behavior doesn’t depend on the state the post is in, so it’s not part of the state pattern. The `add_text` method doesn’t interact with the `state` field at all, but it is part of the behavior we want to support. ### Ensuring the Content of a Draft Post Is Empty Even after we’ve called `add_text` and added some content to our post, we still want the `content` method to return an empty string slice because the post is still in the draft state, as shown on line 7 of Listing 17-11. For now, let’s implement the `content` method with the simplest thing that will fulfill this requirement: always returning an empty string slice. We’ll change this later once we implement the ability to change a post’s state so it can be published. So far, posts can only be in the draft state, so the post content should always be empty. Listing 17-14 shows this placeholder implementation: Filename: src/lib.rs ``` pub struct Post { state: Option<Box<dyn State>>, content: String, } impl Post { // --snip-- pub fn new() -> Post { Post { state: Some(Box::new(Draft {})), content: String::new(), } } pub fn add_text(&mut self, text: &str) { self.content.push_str(text); } pub fn content(&self) -> &str { "" } } trait State {} struct Draft {} impl State for Draft {} ``` Listing 17-14: Adding a placeholder implementation for the `content` method on `Post` that always returns an empty string slice With this added `content` method, everything in Listing 17-11 up to line 7 works as intended. ### Requesting a Review of the Post Changes Its State Next, we need to add functionality to request a review of a post, which should change its state from `Draft` to `PendingReview`. Listing 17-15 shows this code: Filename: src/lib.rs ``` pub struct Post { state: Option<Box<dyn State>>, content: String, } impl Post { // --snip-- pub fn new() -> Post { Post { state: Some(Box::new(Draft {})), content: String::new(), } } pub fn add_text(&mut self, text: &str) { self.content.push_str(text); } pub fn content(&self) -> &str { "" } pub fn request_review(&mut self) { if let Some(s) = self.state.take() { self.state = Some(s.request_review()) } } } trait State { fn request_review(self: Box<Self>) -> Box<dyn State>; } struct Draft {} impl State for Draft { fn request_review(self: Box<Self>) -> Box<dyn State> { Box::new(PendingReview {}) } } struct PendingReview {} impl State for PendingReview { fn request_review(self: Box<Self>) -> Box<dyn State> { self } } ``` Listing 17-15: Implementing `request_review` methods on `Post` and the `State` trait We give `Post` a public method named `request_review` that will take a mutable reference to `self`. Then we call an internal `request_review` method on the current state of `Post`, and this second `request_review` method consumes the current state and returns a new state. We add the `request_review` method to the `State` trait; all types that implement the trait will now need to implement the `request_review` method. Note that rather than having `self`, `&self`, or `&mut self` as the first parameter of the method, we have `self: Box<Self>`. This syntax means the method is only valid when called on a `Box` holding the type. This syntax takes ownership of `Box<Self>`, invalidating the old state so the state value of the `Post` can transform into a new state. To consume the old state, the `request_review` method needs to take ownership of the state value. This is where the `Option` in the `state` field of `Post` comes in: we call the `take` method to take the `Some` value out of the `state` field and leave a `None` in its place, because Rust doesn’t let us have unpopulated fields in structs. This lets us move the `state` value out of `Post` rather than borrowing it. Then we’ll set the post’s `state` value to the result of this operation. We need to set `state` to `None` temporarily rather than setting it directly with code like `self.state = self.state.request_review();` to get ownership of the `state` value. This ensures `Post` can’t use the old `state` value after we’ve transformed it into a new state. The `request_review` method on `Draft` returns a new, boxed instance of a new `PendingReview` struct, which represents the state when a post is waiting for a review. The `PendingReview` struct also implements the `request_review` method but doesn’t do any transformations. Rather, it returns itself, because when we request a review on a post already in the `PendingReview` state, it should stay in the `PendingReview` state. Now we can start seeing the advantages of the state pattern: the `request_review` method on `Post` is the same no matter its `state` value. Each state is responsible for its own rules. We’ll leave the `content` method on `Post` as is, returning an empty string slice. We can now have a `Post` in the `PendingReview` state as well as in the `Draft` state, but we want the same behavior in the `PendingReview` state. Listing 17-11 now works up to line 10! ### Adding `approve` to Change the Behavior of `content` The `approve` method will be similar to the `request_review` method: it will set `state` to the value that the current state says it should have when that state is approved, as shown in Listing 17-16: Filename: src/lib.rs ``` pub struct Post { state: Option<Box<dyn State>>, content: String, } impl Post { // --snip-- pub fn new() -> Post { Post { state: Some(Box::new(Draft {})), content: String::new(), } } pub fn add_text(&mut self, text: &str) { self.content.push_str(text); } pub fn content(&self) -> &str { "" } pub fn request_review(&mut self) { if let Some(s) = self.state.take() { self.state = Some(s.request_review()) } } pub fn approve(&mut self) { if let Some(s) = self.state.take() { self.state = Some(s.approve()) } } } trait State { fn request_review(self: Box<Self>) -> Box<dyn State>; fn approve(self: Box<Self>) -> Box<dyn State>; } struct Draft {} impl State for Draft { // --snip-- fn request_review(self: Box<Self>) -> Box<dyn State> { Box::new(PendingReview {}) } fn approve(self: Box<Self>) -> Box<dyn State> { self } } struct PendingReview {} impl State for PendingReview { // --snip-- fn request_review(self: Box<Self>) -> Box<dyn State> { self } fn approve(self: Box<Self>) -> Box<dyn State> { Box::new(Published {}) } } struct Published {} impl State for Published { fn request_review(self: Box<Self>) -> Box<dyn State> { self } fn approve(self: Box<Self>) -> Box<dyn State> { self } } ``` Listing 17-16: Implementing the `approve` method on `Post` and the `State` trait We add the `approve` method to the `State` trait and add a new struct that implements `State`, the `Published` state. Similar to the way `request_review` on `PendingReview` works, if we call the `approve` method on a `Draft`, it will have no effect because `approve` will return `self`. When we call `approve` on `PendingReview`, it returns a new, boxed instance of the `Published` struct. The `Published` struct implements the `State` trait, and for both the `request_review` method and the `approve` method, it returns itself, because the post should stay in the `Published` state in those cases. Now we need to update the `content` method on `Post`. We want the value returned from `content` to depend on the current state of the `Post`, so we’re going to have the `Post` delegate to a `content` method defined on its `state`, as shown in Listing 17-17: Filename: src/lib.rs ``` pub struct Post { state: Option<Box<dyn State>>, content: String, } impl Post { // --snip-- pub fn new() -> Post { Post { state: Some(Box::new(Draft {})), content: String::new(), } } pub fn add_text(&mut self, text: &str) { self.content.push_str(text); } pub fn content(&self) -> &str { self.state.as_ref().unwrap().content(self) } // --snip-- pub fn request_review(&mut self) { if let Some(s) = self.state.take() { self.state = Some(s.request_review()) } } pub fn approve(&mut self) { if let Some(s) = self.state.take() { self.state = Some(s.approve()) } } } trait State { fn request_review(self: Box<Self>) -> Box<dyn State>; fn approve(self: Box<Self>) -> Box<dyn State>; } struct Draft {} impl State for Draft { fn request_review(self: Box<Self>) -> Box<dyn State> { Box::new(PendingReview {}) } fn approve(self: Box<Self>) -> Box<dyn State> { self } } struct PendingReview {} impl State for PendingReview { fn request_review(self: Box<Self>) -> Box<dyn State> { self } fn approve(self: Box<Self>) -> Box<dyn State> { Box::new(Published {}) } } struct Published {} impl State for Published { fn request_review(self: Box<Self>) -> Box<dyn State> { self } fn approve(self: Box<Self>) -> Box<dyn State> { self } } ``` Listing 17-17: Updating the `content` method on `Post` to delegate to a `content` method on `State` Because the goal is to keep all these rules inside the structs that implement `State`, we call a `content` method on the value in `state` and pass the post instance (that is, `self`) as an argument. Then we return the value that’s returned from using the `content` method on the `state` value. We call the `as_ref` method on the `Option` because we want a reference to the value inside the `Option` rather than ownership of the value. Because `state` is an `Option<Box<dyn State>>`, when we call `as_ref`, an `Option<&Box<dyn State>>` is returned. If we didn’t call `as_ref`, we would get an error because we can’t move `state` out of the borrowed `&self` of the function parameter. We then call the `unwrap` method, which we know will never panic, because we know the methods on `Post` ensure that `state` will always contain a `Some` value when those methods are done. This is one of the cases we talked about in the [“Cases In Which You Have More Information Than the Compiler”](ch09-03-to-panic-or-not-to-panic#cases-in-which-you-have-more-information-than-the-compiler) section of Chapter 9 when we know that a `None` value is never possible, even though the compiler isn’t able to understand that. At this point, when we call `content` on the `&Box<dyn State>`, deref coercion will take effect on the `&` and the `Box` so the `content` method will ultimately be called on the type that implements the `State` trait. That means we need to add `content` to the `State` trait definition, and that is where we’ll put the logic for what content to return depending on which state we have, as shown in Listing 17-18: Filename: src/lib.rs ``` pub struct Post { state: Option<Box<dyn State>>, content: String, } impl Post { pub fn new() -> Post { Post { state: Some(Box::new(Draft {})), content: String::new(), } } pub fn add_text(&mut self, text: &str) { self.content.push_str(text); } pub fn content(&self) -> &str { self.state.as_ref().unwrap().content(self) } pub fn request_review(&mut self) { if let Some(s) = self.state.take() { self.state = Some(s.request_review()) } } pub fn approve(&mut self) { if let Some(s) = self.state.take() { self.state = Some(s.approve()) } } } trait State { // --snip-- fn request_review(self: Box<Self>) -> Box<dyn State>; fn approve(self: Box<Self>) -> Box<dyn State>; fn content<'a>(&self, post: &'a Post) -> &'a str { "" } } // --snip-- struct Draft {} impl State for Draft { fn request_review(self: Box<Self>) -> Box<dyn State> { Box::new(PendingReview {}) } fn approve(self: Box<Self>) -> Box<dyn State> { self } } struct PendingReview {} impl State for PendingReview { fn request_review(self: Box<Self>) -> Box<dyn State> { self } fn approve(self: Box<Self>) -> Box<dyn State> { Box::new(Published {}) } } struct Published {} impl State for Published { // --snip-- fn request_review(self: Box<Self>) -> Box<dyn State> { self } fn approve(self: Box<Self>) -> Box<dyn State> { self } fn content<'a>(&self, post: &'a Post) -> &'a str { &post.content } } ``` Listing 17-18: Adding the `content` method to the `State` trait We add a default implementation for the `content` method that returns an empty string slice. That means we don’t need to implement `content` on the `Draft` and `PendingReview` structs. The `Published` struct will override the `content` method and return the value in `post.content`. Note that we need lifetime annotations on this method, as we discussed in Chapter 10. We’re taking a reference to a `post` as an argument and returning a reference to part of that `post`, so the lifetime of the returned reference is related to the lifetime of the `post` argument. And we’re done—all of Listing 17-11 now works! We’ve implemented the state pattern with the rules of the blog post workflow. The logic related to the rules lives in the state objects rather than being scattered throughout `Post`. > #### Why Not An Enum? > > You may have been wondering why we didn’t use an `enum` with the different possible post states as variants. That’s certainly a possible solution, try it and compare the end results to see which you prefer! One disadvantage of using an enum is every place that checks the value of the enum will need a `match` expression or similar to handle every possible variant. This could get more repetitive than this trait object solution. > > ### Trade-offs of the State Pattern We’ve shown that Rust is capable of implementing the object-oriented state pattern to encapsulate the different kinds of behavior a post should have in each state. The methods on `Post` know nothing about the various behaviors. The way we organized the code, we have to look in only one place to know the different ways a published post can behave: the implementation of the `State` trait on the `Published` struct. If we were to create an alternative implementation that didn’t use the state pattern, we might instead use `match` expressions in the methods on `Post` or even in the `main` code that checks the state of the post and changes behavior in those places. That would mean we would have to look in several places to understand all the implications of a post being in the published state! This would only increase the more states we added: each of those `match` expressions would need another arm. With the state pattern, the `Post` methods and the places we use `Post` don’t need `match` expressions, and to add a new state, we would only need to add a new struct and implement the trait methods on that one struct. The implementation using the state pattern is easy to extend to add more functionality. To see the simplicity of maintaining code that uses the state pattern, try a few of these suggestions: * Add a `reject` method that changes the post’s state from `PendingReview` back to `Draft`. * Require two calls to `approve` before the state can be changed to `Published`. * Allow users to add text content only when a post is in the `Draft` state. Hint: have the state object responsible for what might change about the content but not responsible for modifying the `Post`. One downside of the state pattern is that, because the states implement the transitions between states, some of the states are coupled to each other. If we add another state between `PendingReview` and `Published`, such as `Scheduled`, we would have to change the code in `PendingReview` to transition to `Scheduled` instead. It would be less work if `PendingReview` didn’t need to change with the addition of a new state, but that would mean switching to another design pattern. Another downside is that we’ve duplicated some logic. To eliminate some of the duplication, we might try to make default implementations for the `request_review` and `approve` methods on the `State` trait that return `self`; however, this would violate object safety, because the trait doesn’t know what the concrete `self` will be exactly. We want to be able to use `State` as a trait object, so we need its methods to be object safe. Other duplication includes the similar implementations of the `request_review` and `approve` methods on `Post`. Both methods delegate to the implementation of the same method on the value in the `state` field of `Option` and set the new value of the `state` field to the result. If we had a lot of methods on `Post` that followed this pattern, we might consider defining a macro to eliminate the repetition (see the [“Macros”](ch19-06-macros#macros) section in Chapter 19). By implementing the state pattern exactly as it’s defined for object-oriented languages, we’re not taking as full advantage of Rust’s strengths as we could. Let’s look at some changes we can make to the `blog` crate that can make invalid states and transitions into compile time errors. #### Encoding States and Behavior as Types We’ll show you how to rethink the state pattern to get a different set of trade-offs. Rather than encapsulating the states and transitions completely so outside code has no knowledge of them, we’ll encode the states into different types. Consequently, Rust’s type checking system will prevent attempts to use draft posts where only published posts are allowed by issuing a compiler error. Let’s consider the first part of `main` in Listing 17-11: Filename: src/main.rs ``` use blog::Post; fn main() { let mut post = Post::new(); post.add_text("I ate a salad for lunch today"); assert_eq!("", post.content()); post.request_review(); assert_eq!("", post.content()); post.approve(); assert_eq!("I ate a salad for lunch today", post.content()); } ``` We still enable the creation of new posts in the draft state using `Post::new` and the ability to add text to the post’s content. But instead of having a `content` method on a draft post that returns an empty string, we’ll make it so draft posts don’t have the `content` method at all. That way, if we try to get a draft post’s content, we’ll get a compiler error telling us the method doesn’t exist. As a result, it will be impossible for us to accidentally display draft post content in production, because that code won’t even compile. Listing 17-19 shows the definition of a `Post` struct and a `DraftPost` struct, as well as methods on each: Filename: src/lib.rs ``` pub struct Post { content: String, } pub struct DraftPost { content: String, } impl Post { pub fn new() -> DraftPost { DraftPost { content: String::new(), } } pub fn content(&self) -> &str { &self.content } } impl DraftPost { pub fn add_text(&mut self, text: &str) { self.content.push_str(text); } } ``` Listing 17-19: A `Post` with a `content` method and a `DraftPost` without a `content` method Both the `Post` and `DraftPost` structs have a private `content` field that stores the blog post text. The structs no longer have the `state` field because we’re moving the encoding of the state to the types of the structs. The `Post` struct will represent a published post, and it has a `content` method that returns the `content`. We still have a `Post::new` function, but instead of returning an instance of `Post`, it returns an instance of `DraftPost`. Because `content` is private and there aren’t any functions that return `Post`, it’s not possible to create an instance of `Post` right now. The `DraftPost` struct has an `add_text` method, so we can add text to `content` as before, but note that `DraftPost` does not have a `content` method defined! So now the program ensures all posts start as draft posts, and draft posts don’t have their content available for display. Any attempt to get around these constraints will result in a compiler error. #### Implementing Transitions as Transformations into Different Types So how do we get a published post? We want to enforce the rule that a draft post has to be reviewed and approved before it can be published. A post in the pending review state should still not display any content. Let’s implement these constraints by adding another struct, `PendingReviewPost`, defining the `request_review` method on `DraftPost` to return a `PendingReviewPost`, and defining an `approve` method on `PendingReviewPost` to return a `Post`, as shown in Listing 17-20: Filename: src/lib.rs ``` pub struct Post { content: String, } pub struct DraftPost { content: String, } impl Post { pub fn new() -> DraftPost { DraftPost { content: String::new(), } } pub fn content(&self) -> &str { &self.content } } impl DraftPost { // --snip-- pub fn add_text(&mut self, text: &str) { self.content.push_str(text); } pub fn request_review(self) -> PendingReviewPost { PendingReviewPost { content: self.content, } } } pub struct PendingReviewPost { content: String, } impl PendingReviewPost { pub fn approve(self) -> Post { Post { content: self.content, } } } ``` Listing 17-20: A `PendingReviewPost` that gets created by calling `request_review` on `DraftPost` and an `approve` method that turns a `PendingReviewPost` into a published `Post` The `request_review` and `approve` methods take ownership of `self`, thus consuming the `DraftPost` and `PendingReviewPost` instances and transforming them into a `PendingReviewPost` and a published `Post`, respectively. This way, we won’t have any lingering `DraftPost` instances after we’ve called `request_review` on them, and so forth. The `PendingReviewPost` struct doesn’t have a `content` method defined on it, so attempting to read its content results in a compiler error, as with `DraftPost`. Because the only way to get a published `Post` instance that does have a `content` method defined is to call the `approve` method on a `PendingReviewPost`, and the only way to get a `PendingReviewPost` is to call the `request_review` method on a `DraftPost`, we’ve now encoded the blog post workflow into the type system. But we also have to make some small changes to `main`. The `request_review` and `approve` methods return new instances rather than modifying the struct they’re called on, so we need to add more `let post =` shadowing assignments to save the returned instances. We also can’t have the assertions about the draft and pending review posts’ contents be empty strings, nor do we need them: we can’t compile code that tries to use the content of posts in those states any longer. The updated code in `main` is shown in Listing 17-21: Filename: src/main.rs ``` use blog::Post; fn main() { let mut post = Post::new(); post.add_text("I ate a salad for lunch today"); let post = post.request_review(); let post = post.approve(); assert_eq!("I ate a salad for lunch today", post.content()); } ``` Listing 17-21: Modifications to `main` to use the new implementation of the blog post workflow The changes we needed to make to `main` to reassign `post` mean that this implementation doesn’t quite follow the object-oriented state pattern anymore: the transformations between the states are no longer encapsulated entirely within the `Post` implementation. However, our gain is that invalid states are now impossible because of the type system and the type checking that happens at compile time! This ensures that certain bugs, such as display of the content of an unpublished post, will be discovered before they make it to production. Try the tasks suggested at the start of this section on the `blog` crate as it is after Listing 17-21 to see what you think about the design of this version of the code. Note that some of the tasks might be completed already in this design. We’ve seen that even though Rust is capable of implementing object-oriented design patterns, other patterns, such as encoding state into the type system, are also available in Rust. These patterns have different trade-offs. Although you might be very familiar with object-oriented patterns, rethinking the problem to take advantage of Rust’s features can provide benefits, such as preventing some bugs at compile time. Object-oriented patterns won’t always be the best solution in Rust due to certain features, like ownership, that object-oriented languages don’t have. Summary ------- No matter whether or not you think Rust is an object-oriented language after reading this chapter, you now know that you can use trait objects to get some object-oriented features in Rust. Dynamic dispatch can give your code some flexibility in exchange for a bit of runtime performance. You can use this flexibility to implement object-oriented patterns that can help your code’s maintainability. Rust also has other features, like ownership, that object-oriented languages don’t have. An object-oriented pattern won’t always be the best way to take advantage of Rust’s strengths, but is an available option. Next, we’ll look at patterns, which are another of Rust’s features that enable lots of flexibility. We’ve looked at them briefly throughout the book but haven’t seen their full capability yet. Let’s go!
programming_docs
rust Fearless Concurrency Fearless Concurrency ==================== Handling concurrent programming safely and efficiently is another of Rust’s major goals. *Concurrent programming*, where different parts of a program execute independently, and *parallel programming*, where different parts of a program execute at the same time, are becoming increasingly important as more computers take advantage of their multiple processors. Historically, programming in these contexts has been difficult and error prone: Rust hopes to change that. Initially, the Rust team thought that ensuring memory safety and preventing concurrency problems were two separate challenges to be solved with different methods. Over time, the team discovered that the ownership and type systems are a powerful set of tools to help manage memory safety *and* concurrency problems! By leveraging ownership and type checking, many concurrency errors are compile-time errors in Rust rather than runtime errors. Therefore, rather than making you spend lots of time trying to reproduce the exact circumstances under which a runtime concurrency bug occurs, incorrect code will refuse to compile and present an error explaining the problem. As a result, you can fix your code while you’re working on it rather than potentially after it has been shipped to production. We’ve nicknamed this aspect of Rust *fearless* *concurrency*. Fearless concurrency allows you to write code that is free of subtle bugs and is easy to refactor without introducing new bugs. > Note: For simplicity’s sake, we’ll refer to many of the problems as *concurrent* rather than being more precise by saying *concurrent and/or parallel*. If this book were about concurrency and/or parallelism, we’d be more specific. For this chapter, please mentally substitute *concurrent and/or parallel* whenever we use *concurrent*. > > Many languages are dogmatic about the solutions they offer for handling concurrent problems. For example, Erlang has elegant functionality for message-passing concurrency but has only obscure ways to share state between threads. Supporting only a subset of possible solutions is a reasonable strategy for higher-level languages, because a higher-level language promises benefits from giving up some control to gain abstractions. However, lower-level languages are expected to provide the solution with the best performance in any given situation and have fewer abstractions over the hardware. Therefore, Rust offers a variety of tools for modeling problems in whatever way is appropriate for your situation and requirements. Here are the topics we’ll cover in this chapter: * How to create threads to run multiple pieces of code at the same time * *Message-passing* concurrency, where channels send messages between threads * *Shared-state* concurrency, where multiple threads have access to some piece of data * The `Sync` and `Send` traits, which extend Rust’s concurrency guarantees to user-defined types as well as types provided by the standard library rust Object-Oriented Programming Features of Rust Object-Oriented Programming Features of Rust ============================================ Object-oriented programming (OOP) is a way of modeling programs. Objects as a programmatic concept were introduced in the programming language Simula in the 1960s. Those objects influenced Alan Kay’s programming architecture in which objects pass messages to each other. To describe this architecture, he coined the term *object-oriented programming* in 1967. Many competing definitions describe what OOP is, and by some of these definitions Rust is object-oriented, but by others it is not. In this chapter, we’ll explore certain characteristics that are commonly considered object-oriented and how those characteristics translate to idiomatic Rust. We’ll then show you how to implement an object-oriented design pattern in Rust and discuss the trade-offs of doing so versus implementing a solution using some of Rust’s strengths instead. rust Pattern Syntax Pattern Syntax ============== In this section, we gather all the syntax valid in patterns and discuss why and when you might want to use each one. ### Matching Literals As you saw in Chapter 6, you can match patterns against literals directly. The following code gives some examples: ``` fn main() { let x = 1; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), _ => println!("anything"), } } ``` This code prints `one` because the value in `x` is 1. This syntax is useful when you want your code to take an action if it gets a particular concrete value. ### Matching Named Variables Named variables are irrefutable patterns that match any value, and we’ve used them many times in the book. However, there is a complication when you use named variables in `match` expressions. Because `match` starts a new scope, variables declared as part of a pattern inside the `match` expression will shadow those with the same name outside the `match` construct, as is the case with all variables. In Listing 18-11, we declare a variable named `x` with the value `Some(5)` and a variable `y` with the value `10`. We then create a `match` expression on the value `x`. Look at the patterns in the match arms and `println!` at the end, and try to figure out what the code will print before running this code or reading further. Filename: src/main.rs ``` fn main() { let x = Some(5); let y = 10; match x { Some(50) => println!("Got 50"), Some(y) => println!("Matched, y = {y}"), _ => println!("Default case, x = {:?}", x), } println!("at the end: x = {:?}, y = {y}", x); } ``` Listing 18-11: A `match` expression with an arm that introduces a shadowed variable `y` Let’s walk through what happens when the `match` expression runs. The pattern in the first match arm doesn’t match the defined value of `x`, so the code continues. The pattern in the second match arm introduces a new variable named `y` that will match any value inside a `Some` value. Because we’re in a new scope inside the `match` expression, this is a new `y` variable, not the `y` we declared at the beginning with the value 10. This new `y` binding will match any value inside a `Some`, which is what we have in `x`. Therefore, this new `y` binds to the inner value of the `Some` in `x`. That value is `5`, so the expression for that arm executes and prints `Matched, y = 5`. If `x` had been a `None` value instead of `Some(5)`, the patterns in the first two arms wouldn’t have matched, so the value would have matched to the underscore. We didn’t introduce the `x` variable in the pattern of the underscore arm, so the `x` in the expression is still the outer `x` that hasn’t been shadowed. In this hypothetical case, the `match` would print `Default case, x = None`. When the `match` expression is done, its scope ends, and so does the scope of the inner `y`. The last `println!` produces `at the end: x = Some(5), y = 10`. To create a `match` expression that compares the values of the outer `x` and `y`, rather than introducing a shadowed variable, we would need to use a match guard conditional instead. We’ll talk about match guards later in the [“Extra Conditionals with Match Guards”](#extra-conditionals-with-match-guards) section. ### Multiple Patterns In `match` expressions, you can match multiple patterns using the `|` syntax, which is the pattern *or* operator. For example, in the following code we match the value of `x` against the match arms, the first of which has an *or* option, meaning if the value of `x` matches either of the values in that arm, that arm’s code will run: ``` fn main() { let x = 1; match x { 1 | 2 => println!("one or two"), 3 => println!("three"), _ => println!("anything"), } } ``` This code prints `one or two`. ### Matching Ranges of Values with `..=` The `..=` syntax allows us to match to an inclusive range of values. In the following code, when a pattern matches any of the values within the given range, that arm will execute: ``` fn main() { let x = 5; match x { 1..=5 => println!("one through five"), _ => println!("something else"), } } ``` If `x` is 1, 2, 3, 4, or 5, the first arm will match. This syntax is more convenient for multiple match values than using the `|` operator to express the same idea; if we were to use `|` we would have to specify `1 | 2 | 3 | 4 | 5`. Specifying a range is much shorter, especially if we want to match, say, any number between 1 and 1,000! The compiler checks that the range isn’t empty at compile time, and because the only types for which Rust can tell if a range is empty or not are `char` and numeric values, ranges are only allowed with numeric or `char` values. Here is an example using ranges of `char` values: ``` fn main() { let x = 'c'; match x { 'a'..='j' => println!("early ASCII letter"), 'k'..='z' => println!("late ASCII letter"), _ => println!("something else"), } } ``` Rust can tell that `'c'` is within the first pattern’s range and prints `early ASCII letter`. ### Destructuring to Break Apart Values We can also use patterns to destructure structs, enums, and tuples to use different parts of these values. Let’s walk through each value. #### Destructuring Structs Listing 18-12 shows a `Point` struct with two fields, `x` and `y`, that we can break apart using a pattern with a `let` statement. Filename: src/main.rs ``` struct Point { x: i32, y: i32, } fn main() { let p = Point { x: 0, y: 7 }; let Point { x: a, y: b } = p; assert_eq!(0, a); assert_eq!(7, b); } ``` Listing 18-12: Destructuring a struct’s fields into separate variables This code creates the variables `a` and `b` that match the values of the `x` and `y` fields of the `p` struct. This example shows that the names of the variables in the pattern don’t have to match the field names of the struct. However, it’s common to match the variable names to the field names to make it easier to remember which variables came from which fields. Because of this common usage, and because writing `let Point { x: x, y: y } = p;` contains a lot of duplication, Rust has a shorthand for patterns that match struct fields: you only need to list the name of the struct field, and the variables created from the pattern will have the same names. Listing 18-13 behaves in the same way as the code in Listing 18-12, but the variables created in the `let` pattern are `x` and `y` instead of `a` and `b`. Filename: src/main.rs ``` struct Point { x: i32, y: i32, } fn main() { let p = Point { x: 0, y: 7 }; let Point { x, y } = p; assert_eq!(0, x); assert_eq!(7, y); } ``` Listing 18-13: Destructuring struct fields using struct field shorthand This code creates the variables `x` and `y` that match the `x` and `y` fields of the `p` variable. The outcome is that the variables `x` and `y` contain the values from the `p` struct. We can also destructure with literal values as part of the struct pattern rather than creating variables for all the fields. Doing so allows us to test some of the fields for particular values while creating variables to destructure the other fields. In Listing 18-14, we have a `match` expression that separates `Point` values into three cases: points that lie directly on the `x` axis (which is true when `y = 0`), on the `y` axis (`x = 0`), or neither. Filename: src/main.rs ``` struct Point { x: i32, y: i32, } fn main() { let p = Point { x: 0, y: 7 }; match p { Point { x, y: 0 } => println!("On the x axis at {}", x), Point { x: 0, y } => println!("On the y axis at {}", y), Point { x, y } => println!("On neither axis: ({}, {})", x, y), } } ``` Listing 18-14: Destructuring and matching literal values in one pattern The first arm will match any point that lies on the `x` axis by specifying that the `y` field matches if its value matches the literal `0`. The pattern still creates an `x` variable that we can use in the code for this arm. Similarly, the second arm matches any point on the `y` axis by specifying that the `x` field matches if its value is `0` and creates a variable `y` for the value of the `y` field. The third arm doesn’t specify any literals, so it matches any other `Point` and creates variables for both the `x` and `y` fields. In this example, the value `p` matches the second arm by virtue of `x` containing a 0, so this code will print `On the y axis at 7`. Remember that a `match` expression stops checking arms once it has found the first matching pattern, so even though `Point { x: 0, y: 0}` is on the `x` axis and the `y` axis, this code would only print `On the x axis at 0`. #### Destructuring Enums We've destructured enums in this book (for example, Listing 6-5 in Chapter 6), but haven’t yet explicitly discussed that the pattern to destructure an enum corresponds to the way the data stored within the enum is defined. As an example, in Listing 18-15 we use the `Message` enum from Listing 6-2 and write a `match` with patterns that will destructure each inner value. Filename: src/main.rs ``` enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } fn main() { let msg = Message::ChangeColor(0, 160, 255); match msg { Message::Quit => { println!("The Quit variant has no data to destructure.") } Message::Move { x, y } => { println!( "Move in the x direction {} and in the y direction {}", x, y ); } Message::Write(text) => println!("Text message: {}", text), Message::ChangeColor(r, g, b) => println!( "Change the color to red {}, green {}, and blue {}", r, g, b ), } } ``` Listing 18-15: Destructuring enum variants that hold different kinds of values This code will print `Change the color to red 0, green 160, and blue 255`. Try changing the value of `msg` to see the code from the other arms run. For enum variants without any data, like `Message::Quit`, we can’t destructure the value any further. We can only match on the literal `Message::Quit` value, and no variables are in that pattern. For struct-like enum variants, such as `Message::Move`, we can use a pattern similar to the pattern we specify to match structs. After the variant name, we place curly brackets and then list the fields with variables so we break apart the pieces to use in the code for this arm. Here we use the shorthand form as we did in Listing 18-13. For tuple-like enum variants, like `Message::Write` that holds a tuple with one element and `Message::ChangeColor` that holds a tuple with three elements, the pattern is similar to the pattern we specify to match tuples. The number of variables in the pattern must match the number of elements in the variant we’re matching. #### Destructuring Nested Structs and Enums So far, our examples have all been matching structs or enums one level deep, but matching can work on nested items too! For example, we can refactor the code in Listing 18-15 to support RGB and HSV colors in the `ChangeColor` message, as shown in Listing 18-16. ``` enum Color { Rgb(i32, i32, i32), Hsv(i32, i32, i32), } enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(Color), } fn main() { let msg = Message::ChangeColor(Color::Hsv(0, 160, 255)); match msg { Message::ChangeColor(Color::Rgb(r, g, b)) => println!( "Change the color to red {}, green {}, and blue {}", r, g, b ), Message::ChangeColor(Color::Hsv(h, s, v)) => println!( "Change the color to hue {}, saturation {}, and value {}", h, s, v ), _ => (), } } ``` Listing 18-16: Matching on nested enums The pattern of the first arm in the `match` expression matches a `Message::ChangeColor` enum variant that contains a `Color::Rgb` variant; then the pattern binds to the three inner `i32` values. The pattern of the second arm also matches a `Message::ChangeColor` enum variant, but the inner enum matches `Color::Hsv` instead. We can specify these complex conditions in one `match` expression, even though two enums are involved. #### Destructuring Structs and Tuples We can mix, match, and nest destructuring patterns in even more complex ways. The following example shows a complicated destructure where we nest structs and tuples inside a tuple and destructure all the primitive values out: ``` fn main() { struct Point { x: i32, y: i32, } let ((feet, inches), Point { x, y }) = ((3, 10), Point { x: 3, y: -10 }); } ``` This code lets us break complex types into their component parts so we can use the values we’re interested in separately. Destructuring with patterns is a convenient way to use pieces of values, such as the value from each field in a struct, separately from each other. ### Ignoring Values in a Pattern You’ve seen that it’s sometimes useful to ignore values in a pattern, such as in the last arm of a `match`, to get a catchall that doesn’t actually do anything but does account for all remaining possible values. There are a few ways to ignore entire values or parts of values in a pattern: using the `_` pattern (which you’ve seen), using the `_` pattern within another pattern, using a name that starts with an underscore, or using `..` to ignore remaining parts of a value. Let’s explore how and why to use each of these patterns. #### Ignoring an Entire Value with `_` We’ve used the underscore as a wildcard pattern that will match any value but not bind to the value. This is especially useful as the last arm in a `match` expression, but we can also use it in any pattern, including function parameters, as shown in Listing 18-17. Filename: src/main.rs ``` fn foo(_: i32, y: i32) { println!("This code only uses the y parameter: {}", y); } fn main() { foo(3, 4); } ``` Listing 18-17: Using `_` in a function signature This code will completely ignore the value `3` passed as the first argument, and will print `This code only uses the y parameter: 4`. In most cases when you no longer need a particular function parameter, you would change the signature so it doesn’t include the unused parameter. Ignoring a function parameter can be especially useful in cases when, for example, you're implementing a trait when you need a certain type signature but the function body in your implementation doesn’t need one of the parameters. You then avoid getting a compiler warning about unused function parameters, as you would if you used a name instead. #### Ignoring Parts of a Value with a Nested `_` We can also use `_` inside another pattern to ignore just part of a value, for example, when we want to test for only part of a value but have no use for the other parts in the corresponding code we want to run. Listing 18-18 shows code responsible for managing a setting’s value. The business requirements are that the user should not be allowed to overwrite an existing customization of a setting but can unset the setting and give it a value if it is currently unset. ``` fn main() { let mut setting_value = Some(5); let new_setting_value = Some(10); match (setting_value, new_setting_value) { (Some(_), Some(_)) => { println!("Can't overwrite an existing customized value"); } _ => { setting_value = new_setting_value; } } println!("setting is {:?}", setting_value); } ``` Listing 18-18: Using an underscore within patterns that match `Some` variants when we don’t need to use the value inside the `Some` This code will print `Can't overwrite an existing customized value` and then `setting is Some(5)`. In the first match arm, we don’t need to match on or use the values inside either `Some` variant, but we do need to test for the case when `setting_value` and `new_setting_value` are the `Some` variant. In that case, we print the reason for not changing `setting_value`, and it doesn’t get changed. In all other cases (if either `setting_value` or `new_setting_value` are `None`) expressed by the `_` pattern in the second arm, we want to allow `new_setting_value` to become `setting_value`. We can also use underscores in multiple places within one pattern to ignore particular values. Listing 18-19 shows an example of ignoring the second and fourth values in a tuple of five items. ``` fn main() { let numbers = (2, 4, 8, 16, 32); match numbers { (first, _, third, _, fifth) => { println!("Some numbers: {first}, {third}, {fifth}") } } } ``` Listing 18-19: Ignoring multiple parts of a tuple This code will print `Some numbers: 2, 8, 32`, and the values 4 and 16 will be ignored. #### Ignoring an Unused Variable by Starting Its Name with `_` If you create a variable but don’t use it anywhere, Rust will usually issue a warning because an unused variable could be a bug. However, sometimes it’s useful to be able to create a variable you won’t use yet, such as when you’re prototyping or just starting a project. In this situation, you can tell Rust not to warn you about the unused variable by starting the name of the variable with an underscore. In Listing 18-20, we create two unused variables, but when we compile this code, we should only get a warning about one of them. Filename: src/main.rs ``` fn main() { let _x = 5; let y = 10; } ``` Listing 18-20: Starting a variable name with an underscore to avoid getting unused variable warnings Here we get a warning about not using the variable `y`, but we don’t get a warning about not using `_x`. Note that there is a subtle difference between using only `_` and using a name that starts with an underscore. The syntax `_x` still binds the value to the variable, whereas `_` doesn’t bind at all. To show a case where this distinction matters, Listing 18-21 will provide us with an error. ``` fn main() { let s = Some(String::from("Hello!")); if let Some(_s) = s { println!("found a string"); } println!("{:?}", s); } ``` Listing 18-21: An unused variable starting with an underscore still binds the value, which might take ownership of the value We’ll receive an error because the `s` value will still be moved into `_s`, which prevents us from using `s` again. However, using the underscore by itself doesn’t ever bind to the value. Listing 18-22 will compile without any errors because `s` doesn’t get moved into `_`. ``` fn main() { let s = Some(String::from("Hello!")); if let Some(_) = s { println!("found a string"); } println!("{:?}", s); } ``` Listing 18-22: Using an underscore does not bind the value This code works just fine because we never bind `s` to anything; it isn’t moved. #### Ignoring Remaining Parts of a Value with `..` With values that have many parts, we can use the `..` syntax to use specific parts and ignore the rest, avoiding the need to list underscores for each ignored value. The `..` pattern ignores any parts of a value that we haven’t explicitly matched in the rest of the pattern. In Listing 18-23, we have a `Point` struct that holds a coordinate in three-dimensional space. In the `match` expression, we want to operate only on the `x` coordinate and ignore the values in the `y` and `z` fields. ``` fn main() { struct Point { x: i32, y: i32, z: i32, } let origin = Point { x: 0, y: 0, z: 0 }; match origin { Point { x, .. } => println!("x is {}", x), } } ``` Listing 18-23: Ignoring all fields of a `Point` except for `x` by using `..` We list the `x` value and then just include the `..` pattern. This is quicker than having to list `y: _` and `z: _`, particularly when we’re working with structs that have lots of fields in situations where only one or two fields are relevant. The syntax `..` will expand to as many values as it needs to be. Listing 18-24 shows how to use `..` with a tuple. Filename: src/main.rs ``` fn main() { let numbers = (2, 4, 8, 16, 32); match numbers { (first, .., last) => { println!("Some numbers: {first}, {last}"); } } } ``` Listing 18-24: Matching only the first and last values in a tuple and ignoring all other values In this code, the first and last value are matched with `first` and `last`. The `..` will match and ignore everything in the middle. However, using `..` must be unambiguous. If it is unclear which values are intended for matching and which should be ignored, Rust will give us an error. Listing 18-25 shows an example of using `..` ambiguously, so it will not compile. Filename: src/main.rs ``` fn main() { let numbers = (2, 4, 8, 16, 32); match numbers { (.., second, ..) => { println!("Some numbers: {}", second) }, } } ``` Listing 18-25: An attempt to use `..` in an ambiguous way When we compile this example, we get this error: ``` $ cargo run Compiling patterns v0.1.0 (file:///projects/patterns) error: `..` can only be used once per tuple pattern --> src/main.rs:5:22 | 5 | (.., second, ..) => { | -- ^^ can only be used once per tuple pattern | | | previously used here error: could not compile `patterns` due to previous error ``` It’s impossible for Rust to determine how many values in the tuple to ignore before matching a value with `second` and then how many further values to ignore thereafter. This code could mean that we want to ignore `2`, bind `second` to `4`, and then ignore `8`, `16`, and `32`; or that we want to ignore `2` and `4`, bind `second` to `8`, and then ignore `16` and `32`; and so forth. The variable name `second` doesn’t mean anything special to Rust, so we get a compiler error because using `..` in two places like this is ambiguous. ### Extra Conditionals with Match Guards A *match guard* is an additional `if` condition, specified after the pattern in a `match` arm, that must also match for that arm to be chosen. Match guards are useful for expressing more complex ideas than a pattern alone allows. The condition can use variables created in the pattern. Listing 18-26 shows a `match` where the first arm has the pattern `Some(x)` and also has a match guard of `if x % 2 == 0` (which will be true if the number is even). ``` fn main() { let num = Some(4); match num { Some(x) if x % 2 == 0 => println!("The number {} is even", x), Some(x) => println!("The number {} is odd", x), None => (), } } ``` Listing 18-26: Adding a match guard to a pattern This example will print `The number 4 is even`. When `num` is compared to the pattern in the first arm, it matches, because `Some(4)` matches `Some(x)`. Then the match guard checks whether the remainder of dividing `x` by 2 is equal to 0, and because it is, the first arm is selected. If `num` had been `Some(5)` instead, the match guard in the first arm would have been false because the remainder of 5 divided by 2 is 1, which is not equal to 0. Rust would then go to the second arm, which would match because the second arm doesn’t have a match guard and therefore matches any `Some` variant. There is no way to express the `if x % 2 == 0` condition within a pattern, so the match guard gives us the ability to express this logic. The downside of this additional expressiveness is that the compiler doesn't try to check for exhaustiveness when match guard expressions are involved. In Listing 18-11, we mentioned that we could use match guards to solve our pattern-shadowing problem. Recall that we created a new variable inside the pattern in the `match` expression instead of using the variable outside the `match`. That new variable meant we couldn’t test against the value of the outer variable. Listing 18-27 shows how we can use a match guard to fix this problem. Filename: src/main.rs ``` fn main() { let x = Some(5); let y = 10; match x { Some(50) => println!("Got 50"), Some(n) if n == y => println!("Matched, n = {n}"), _ => println!("Default case, x = {:?}", x), } println!("at the end: x = {:?}, y = {y}", x); } ``` Listing 18-27: Using a match guard to test for equality with an outer variable This code will now print `Default case, x = Some(5)`. The pattern in the second match arm doesn’t introduce a new variable `y` that would shadow the outer `y`, meaning we can use the outer `y` in the match guard. Instead of specifying the pattern as `Some(y)`, which would have shadowed the outer `y`, we specify `Some(n)`. This creates a new variable `n` that doesn’t shadow anything because there is no `n` variable outside the `match`. The match guard `if n == y` is not a pattern and therefore doesn’t introduce new variables. This `y` *is* the outer `y` rather than a new shadowed `y`, and we can look for a value that has the same value as the outer `y` by comparing `n` to `y`. You can also use the *or* operator `|` in a match guard to specify multiple patterns; the match guard condition will apply to all the patterns. Listing 18-28 shows the precedence when combining a pattern that uses `|` with a match guard. The important part of this example is that the `if y` match guard applies to `4`, `5`, *and* `6`, even though it might look like `if y` only applies to `6`. ``` fn main() { let x = 4; let y = false; match x { 4 | 5 | 6 if y => println!("yes"), _ => println!("no"), } } ``` Listing 18-28: Combining multiple patterns with a match guard The match condition states that the arm only matches if the value of `x` is equal to `4`, `5`, or `6` *and* if `y` is `true`. When this code runs, the pattern of the first arm matches because `x` is `4`, but the match guard `if y` is false, so the first arm is not chosen. The code moves on to the second arm, which does match, and this program prints `no`. The reason is that the `if` condition applies to the whole pattern `4 | 5 | 6`, not only to the last value `6`. In other words, the precedence of a match guard in relation to a pattern behaves like this: ``` (4 | 5 | 6) if y => ... ``` rather than this: ``` 4 | 5 | (6 if y) => ... ``` After running the code, the precedence behavior is evident: if the match guard were applied only to the final value in the list of values specified using the `|` operator, the arm would have matched and the program would have printed `yes`. ### `@` Bindings The *at* operator `@` lets us create a variable that holds a value at the same time as we’re testing that value for a pattern match. In Listing 18-29, we want to test that a `Message::Hello` `id` field is within the range `3..=7`. We also want to bind the value to the variable `id_variable` so we can use it in the code associated with the arm. We could name this variable `id`, the same as the field, but for this example we’ll use a different name. ``` fn main() { enum Message { Hello { id: i32 }, } let msg = Message::Hello { id: 5 }; match msg { Message::Hello { id: id_variable @ 3..=7, } => println!("Found an id in range: {}", id_variable), Message::Hello { id: 10..=12 } => { println!("Found an id in another range") } Message::Hello { id } => println!("Found some other id: {}", id), } } ``` Listing 18-29: Using `@` to bind to a value in a pattern while also testing it This example will print `Found an id in range: 5`. By specifying `id_variable @` before the range `3..=7`, we’re capturing whatever value matched the range while also testing that the value matched the range pattern. In the second arm, where we only have a range specified in the pattern, the code associated with the arm doesn’t have a variable that contains the actual value of the `id` field. The `id` field’s value could have been 10, 11, or 12, but the code that goes with that pattern doesn’t know which it is. The pattern code isn’t able to use the value from the `id` field, because we haven’t saved the `id` value in a variable. In the last arm, where we’ve specified a variable without a range, we do have the value available to use in the arm’s code in a variable named `id`. The reason is that we’ve used the struct field shorthand syntax. But we haven’t applied any test to the value in the `id` field in this arm, as we did with the first two arms: any value would match this pattern. Using `@` lets us test a value and save it in a variable within one pattern. Summary ------- Rust’s patterns are very useful in distinguishing between different kinds of data. When used in `match` expressions, Rust ensures your patterns cover every possible value, or your program won’t compile. Patterns in `let` statements and function parameters make those constructs more useful, enabling the destructuring of values into smaller parts at the same time as assigning to variables. We can create simple or complex patterns to suit our needs. Next, for the penultimate chapter of the book, we’ll look at some advanced aspects of a variety of Rust’s features.
programming_docs
rust Using Message Passing to Transfer Data Between Threads Using Message Passing to Transfer Data Between Threads ====================================================== One increasingly popular approach to ensuring safe concurrency is *message passing*, where threads or actors communicate by sending each other messages containing data. Here’s the idea in a slogan from [the Go language documentation](https://golang.org/doc/effective_go.html#concurrency): “Do not communicate by sharing memory; instead, share memory by communicating.” To accomplish message-sending concurrency, Rust's standard library provides an implementation of *channels*. A channel is a general programming concept by which data is sent from one thread to another. You can imagine a channel in programming as being like a directional channel of water, such as a stream or a river. If you put something like a rubber duck into a river, it will travel downstream to the end of the waterway. A channel has two halves: a transmitter and a receiver. The transmitter half is the upstream location where you put rubber ducks into the river, and the receiver half is where the rubber duck ends up downstream. One part of your code calls methods on the transmitter with the data you want to send, and another part checks the receiving end for arriving messages. A channel is said to be *closed* if either the transmitter or receiver half is dropped. Here, we’ll work up to a program that has one thread to generate values and send them down a channel, and another thread that will receive the values and print them out. We’ll be sending simple values between threads using a channel to illustrate the feature. Once you’re familiar with the technique, you could use channels for any threads that need to communicate between each other, such as a chat system or a system where many threads perform parts of a calculation and send the parts to one thread that aggregates the results. First, in Listing 16-6, we’ll create a channel but not do anything with it. Note that this won’t compile yet because Rust can’t tell what type of values we want to send over the channel. Filename: src/main.rs ``` use std::sync::mpsc; fn main() { let (tx, rx) = mpsc::channel(); } ``` Listing 16-6: Creating a channel and assigning the two halves to `tx` and `rx` We create a new channel using the `mpsc::channel` function; `mpsc` stands for *multiple producer, single consumer*. In short, the way Rust’s standard library implements channels means a channel can have multiple *sending* ends that produce values but only one *receiving* end that consumes those values. Imagine multiple streams flowing together into one big river: everything sent down any of the streams will end up in one river at the end. We’ll start with a single producer for now, but we’ll add multiple producers when we get this example working. The `mpsc::channel` function returns a tuple, the first element of which is the sending end--the transmitter--and the second element is the receiving end--the receiver. The abbreviations `tx` and `rx` are traditionally used in many fields for *transmitter* and *receiver* respectively, so we name our variables as such to indicate each end. We’re using a `let` statement with a pattern that destructures the tuples; we’ll discuss the use of patterns in `let` statements and destructuring in Chapter 18. For now, know that using a `let` statement this way is a convenient approach to extract the pieces of the tuple returned by `mpsc::channel`. Let’s move the transmitting end into a spawned thread and have it send one string so the spawned thread is communicating with the main thread, as shown in Listing 16-7. This is like putting a rubber duck in the river upstream or sending a chat message from one thread to another. Filename: src/main.rs ``` use std::sync::mpsc; use std::thread; fn main() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("hi"); tx.send(val).unwrap(); }); } ``` Listing 16-7: Moving `tx` to a spawned thread and sending “hi” Again, we’re using `thread::spawn` to create a new thread and then using `move` to move `tx` into the closure so the spawned thread owns `tx`. The spawned thread needs to own the transmitter to be able to send messages through the channel. The transmitter has a `send` method that takes the value we want to send. The `send` method returns a `Result<T, E>` type, so if the receiver has already been dropped and there’s nowhere to send a value, the send operation will return an error. In this example, we’re calling `unwrap` to panic in case of an error. But in a real application, we would handle it properly: return to Chapter 9 to review strategies for proper error handling. In Listing 16-8, we’ll get the value from the receiver in the main thread. This is like retrieving the rubber duck from the water at the end of the river or receiving a chat message. Filename: src/main.rs ``` use std::sync::mpsc; use std::thread; fn main() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("hi"); tx.send(val).unwrap(); }); let received = rx.recv().unwrap(); println!("Got: {}", received); } ``` Listing 16-8: Receiving the value “hi” in the main thread and printing it The receiver has two useful methods: `recv` and `try_recv`. We’re using `recv`, short for *receive*, which will block the main thread’s execution and wait until a value is sent down the channel. Once a value is sent, `recv` will return it in a `Result<T, E>`. When the transmitter closes, `recv` will return an error to signal that no more values will be coming. The `try_recv` method doesn’t block, but will instead return a `Result<T, E>` immediately: an `Ok` value holding a message if one is available and an `Err` value if there aren’t any messages this time. Using `try_recv` is useful if this thread has other work to do while waiting for messages: we could write a loop that calls `try_recv` every so often, handles a message if one is available, and otherwise does other work for a little while until checking again. We’ve used `recv` in this example for simplicity; we don’t have any other work for the main thread to do other than wait for messages, so blocking the main thread is appropriate. When we run the code in Listing 16-8, we’ll see the value printed from the main thread: ``` Got: hi ``` Perfect! ### Channels and Ownership Transference The ownership rules play a vital role in message sending because they help you write safe, concurrent code. Preventing errors in concurrent programming is the advantage of thinking about ownership throughout your Rust programs. Let’s do an experiment to show how channels and ownership work together to prevent problems: we’ll try to use a `val` value in the spawned thread *after* we’ve sent it down the channel. Try compiling the code in Listing 16-9 to see why this code isn’t allowed: Filename: src/main.rs ``` use std::sync::mpsc; use std::thread; fn main() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("hi"); tx.send(val).unwrap(); println!("val is {}", val); }); let received = rx.recv().unwrap(); println!("Got: {}", received); } ``` Listing 16-9: Attempting to use `val` after we’ve sent it down the channel Here, we try to print `val` after we’ve sent it down the channel via `tx.send`. Allowing this would be a bad idea: once the value has been sent to another thread, that thread could modify or drop it before we try to use the value again. Potentially, the other thread’s modifications could cause errors or unexpected results due to inconsistent or nonexistent data. However, Rust gives us an error if we try to compile the code in Listing 16-9: ``` $ cargo run Compiling message-passing v0.1.0 (file:///projects/message-passing) error[E0382]: borrow of moved value: `val` --> src/main.rs:10:31 | 8 | let val = String::from("hi"); | --- move occurs because `val` has type `String`, which does not implement the `Copy` trait 9 | tx.send(val).unwrap(); | --- value moved here 10 | println!("val is {}", val); | ^^^ value borrowed here after move | = note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info) For more information about this error, try `rustc --explain E0382`. error: could not compile `message-passing` due to previous error ``` Our concurrency mistake has caused a compile time error. The `send` function takes ownership of its parameter, and when the value is moved, the receiver takes ownership of it. This stops us from accidentally using the value again after sending it; the ownership system checks that everything is okay. ### Sending Multiple Values and Seeing the Receiver Waiting The code in Listing 16-8 compiled and ran, but it didn’t clearly show us that two separate threads were talking to each other over the channel. In Listing 16-10 we’ve made some modifications that will prove the code in Listing 16-8 is running concurrently: the spawned thread will now send multiple messages and pause for a second between each message. Filename: src/main.rs ``` use std::sync::mpsc; use std::thread; use std::time::Duration; fn main() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("thread"), ]; for val in vals { tx.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); for received in rx { println!("Got: {}", received); } } ``` Listing 16-10: Sending multiple messages and pausing between each This time, the spawned thread has a vector of strings that we want to send to the main thread. We iterate over them, sending each individually, and pause between each by calling the `thread::sleep` function with a `Duration` value of 1 second. In the main thread, we’re not calling the `recv` function explicitly anymore: instead, we’re treating `rx` as an iterator. For each value received, we’re printing it. When the channel is closed, iteration will end. When running the code in Listing 16-10, you should see the following output with a 1-second pause in between each line: ``` Got: hi Got: from Got: the Got: thread ``` Because we don’t have any code that pauses or delays in the `for` loop in the main thread, we can tell that the main thread is waiting to receive values from the spawned thread. ### Creating Multiple Producers by Cloning the Transmitter Earlier we mentioned that `mpsc` was an acronym for *multiple producer, single consumer*. Let’s put `mpsc` to use and expand the code in Listing 16-10 to create multiple threads that all send values to the same receiver. We can do so by cloning the transmitter, as shown in Listing 16-11: Filename: src/main.rs ``` use std::sync::mpsc; use std::thread; use std::time::Duration; fn main() { // --snip-- let (tx, rx) = mpsc::channel(); let tx1 = tx.clone(); thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("thread"), ]; for val in vals { tx1.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); thread::spawn(move || { let vals = vec![ String::from("more"), String::from("messages"), String::from("for"), String::from("you"), ]; for val in vals { tx.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); for received in rx { println!("Got: {}", received); } // --snip-- } ``` Listing 16-11: Sending multiple messages from multiple producers This time, before we create the first spawned thread, we call `clone` on the transmitter. This will give us a new transmitter we can pass to the first spawned thread. We pass the original transmitter to a second spawned thread. This gives us two threads, each sending different messages to the one receiver. When you run the code, your output should look something like this: ``` Got: hi Got: more Got: from Got: messages Got: for Got: the Got: thread Got: you ``` You might see the values in another order, depending on your system. This is what makes concurrency interesting as well as difficult. If you experiment with `thread::sleep`, giving it various values in the different threads, each run will be more nondeterministic and create different output each time. Now that we’ve looked at how channels work, let’s look at a different method of concurrency. rust Functions Functions ========= Functions are prevalent in Rust code. You’ve already seen one of the most important functions in the language: the `main` function, which is the entry point of many programs. You’ve also seen the `fn` keyword, which allows you to declare new functions. Rust code uses *snake case* as the conventional style for function and variable names, in which all letters are lowercase and underscores separate words. Here’s a program that contains an example function definition: Filename: src/main.rs ``` fn main() { println!("Hello, world!"); another_function(); } fn another_function() { println!("Another function."); } ``` We define a function in Rust by entering `fn` followed by a function name and a set of parentheses. The curly brackets tell the compiler where the function body begins and ends. We can call any function we’ve defined by entering its name followed by a set of parentheses. Because `another_function` is defined in the program, it can be called from inside the `main` function. Note that we defined `another_function` *after* the `main` function in the source code; we could have defined it before as well. Rust doesn’t care where you define your functions, only that they’re defined somewhere in a scope that can be seen by the caller. Let’s start a new binary project named *functions* to explore functions further. Place the `another_function` example in *src/main.rs* and run it. You should see the following output: ``` $ cargo run Compiling functions v0.1.0 (file:///projects/functions) Finished dev [unoptimized + debuginfo] target(s) in 0.28s Running `target/debug/functions` Hello, world! Another function. ``` The lines execute in the order in which they appear in the `main` function. First, the “Hello, world!” message prints, and then `another_function` is called and its message is printed. ### Parameters We can define functions to have *parameters*, which are special variables that are part of a function’s signature. When a function has parameters, you can provide it with concrete values for those parameters. Technically, the concrete values are called *arguments*, but in casual conversation, people tend to use the words *parameter* and *argument* interchangeably for either the variables in a function’s definition or the concrete values passed in when you call a function. In this version of `another_function` we add a parameter: Filename: src/main.rs ``` fn main() { another_function(5); } fn another_function(x: i32) { println!("The value of x is: {x}"); } ``` Try running this program; you should get the following output: ``` $ cargo run Compiling functions v0.1.0 (file:///projects/functions) Finished dev [unoptimized + debuginfo] target(s) in 1.21s Running `target/debug/functions` The value of x is: 5 ``` The declaration of `another_function` has one parameter named `x`. The type of `x` is specified as `i32`. When we pass `5` in to `another_function`, the `println!` macro puts `5` where the pair of curly brackets containing `x` was in the format string. In function signatures, you *must* declare the type of each parameter. This is a deliberate decision in Rust’s design: requiring type annotations in function definitions means the compiler almost never needs you to use them elsewhere in the code to figure out what type you mean. The compiler is also able to give more helpful error messages if it knows what types the function expects. When defining multiple parameters, separate the parameter declarations with commas, like this: Filename: src/main.rs ``` fn main() { print_labeled_measurement(5, 'h'); } fn print_labeled_measurement(value: i32, unit_label: char) { println!("The measurement is: {value}{unit_label}"); } ``` This example creates a function named `print_labeled_measurement` with two parameters. The first parameter is named `value` and is an `i32`. The second is named `unit_label` and is type `char`. The function then prints text containing both the `value` and the `unit_label`. Let’s try running this code. Replace the program currently in your *functions* project’s *src/main.rs* file with the preceding example and run it using `cargo run`: ``` $ cargo run Compiling functions v0.1.0 (file:///projects/functions) Finished dev [unoptimized + debuginfo] target(s) in 0.31s Running `target/debug/functions` The measurement is: 5h ``` Because we called the function with `5` as the value for `value` and `'h'` as the value for `unit_label`, the program output contains those values. ### Statements and Expressions Function bodies are made up of a series of statements optionally ending in an expression. So far, the functions we’ve covered haven’t included an ending expression, but you have seen an expression as part of a statement. Because Rust is an expression-based language, this is an important distinction to understand. Other languages don’t have the same distinctions, so let’s look at what statements and expressions are and how their differences affect the bodies of functions. *Statements* are instructions that perform some action and do not return a value. *Expressions* evaluate to a resulting value. Let’s look at some examples. We’ve actually already used statements and expressions. Creating a variable and assigning a value to it with the `let` keyword is a statement. In Listing 3-1, `let y = 6;` is a statement. Filename: src/main.rs ``` fn main() { let y = 6; } ``` Listing 3-1: A `main` function declaration containing one statement Function definitions are also statements; the entire preceding example is a statement in itself. Statements do not return values. Therefore, you can’t assign a `let` statement to another variable, as the following code tries to do; you’ll get an error: Filename: src/main.rs ``` fn main() { let x = (let y = 6); } ``` When you run this program, the error you’ll get looks like this: ``` $ cargo run Compiling functions v0.1.0 (file:///projects/functions) error: expected expression, found statement (`let`) --> src/main.rs:2:14 | 2 | let x = (let y = 6); | ^^^^^^^^^ | = note: variable declaration using `let` is a statement error[E0658]: `let` expressions in this position are unstable --> src/main.rs:2:14 | 2 | let x = (let y = 6); | ^^^^^^^^^ | = note: see issue #53667 <https://github.com/rust-lang/rust/issues/53667> for more information warning: unnecessary parentheses around assigned value --> src/main.rs:2:13 | 2 | let x = (let y = 6); | ^ ^ | = note: `#[warn(unused_parens)]` on by default help: remove these parentheses | 2 - let x = (let y = 6); 2 + let x = let y = 6; | For more information about this error, try `rustc --explain E0658`. warning: `functions` (bin "functions") generated 1 warning error: could not compile `functions` due to 2 previous errors; 1 warning emitted ``` The `let y = 6` statement does not return a value, so there isn’t anything for `x` to bind to. This is different from what happens in other languages, such as C and Ruby, where the assignment returns the value of the assignment. In those languages, you can write `x = y = 6` and have both `x` and `y` have the value `6`; that is not the case in Rust. Expressions evaluate to a value and make up most of the rest of the code that you’ll write in Rust. Consider a math operation, such as `5 + 6`, which is an expression that evaluates to the value `11`. Expressions can be part of statements: in Listing 3-1, the `6` in the statement `let y = 6;` is an expression that evaluates to the value `6`. Calling a function is an expression. Calling a macro is an expression. A new scope block created with curly brackets is an expression, for example: Filename: src/main.rs ``` fn main() { let y = { let x = 3; x + 1 }; println!("The value of y is: {y}"); } ``` This expression: ``` { let x = 3; x + 1 } ``` is a block that, in this case, evaluates to `4`. That value gets bound to `y` as part of the `let` statement. Note that the `x + 1` line doesn’t have a semicolon at the end, unlike most of the lines you’ve seen so far. Expressions do not include ending semicolons. If you add a semicolon to the end of an expression, you turn it into a statement, and it will then not return a value. Keep this in mind as you explore function return values and expressions next. ### Functions with Return Values Functions can return values to the code that calls them. We don’t name return values, but we must declare their type after an arrow (`->`). In Rust, the return value of the function is synonymous with the value of the final expression in the block of the body of a function. You can return early from a function by using the `return` keyword and specifying a value, but most functions return the last expression implicitly. Here’s an example of a function that returns a value: Filename: src/main.rs ``` fn five() -> i32 { 5 } fn main() { let x = five(); println!("The value of x is: {x}"); } ``` There are no function calls, macros, or even `let` statements in the `five` function—just the number `5` by itself. That’s a perfectly valid function in Rust. Note that the function’s return type is specified too, as `-> i32`. Try running this code; the output should look like this: ``` $ cargo run Compiling functions v0.1.0 (file:///projects/functions) Finished dev [unoptimized + debuginfo] target(s) in 0.30s Running `target/debug/functions` The value of x is: 5 ``` The `5` in `five` is the function’s return value, which is why the return type is `i32`. Let’s examine this in more detail. There are two important bits: first, the line `let x = five();` shows that we’re using the return value of a function to initialize a variable. Because the function `five` returns a `5`, that line is the same as the following: ``` #![allow(unused)] fn main() { let x = 5; } ``` Second, the `five` function has no parameters and defines the type of the return value, but the body of the function is a lonely `5` with no semicolon because it’s an expression whose value we want to return. Let’s look at another example: Filename: src/main.rs ``` fn main() { let x = plus_one(5); println!("The value of x is: {x}"); } fn plus_one(x: i32) -> i32 { x + 1 } ``` Running this code will print `The value of x is: 6`. But if we place a semicolon at the end of the line containing `x + 1`, changing it from an expression to a statement, we’ll get an error. Filename: src/main.rs ``` fn main() { let x = plus_one(5); println!("The value of x is: {x}"); } fn plus_one(x: i32) -> i32 { x + 1; } ``` Compiling this code produces an error, as follows: ``` $ cargo run Compiling functions v0.1.0 (file:///projects/functions) error[E0308]: mismatched types --> src/main.rs:7:24 | 7 | fn plus_one(x: i32) -> i32 { | -------- ^^^ expected `i32`, found `()` | | | implicitly returns `()` as its body has no tail or `return` expression 8 | x + 1; | - help: remove this semicolon For more information about this error, try `rustc --explain E0308`. error: could not compile `functions` due to previous error ``` The main error message, “mismatched types,” reveals the core issue with this code. The definition of the function `plus_one` says that it will return an `i32`, but statements don’t evaluate to a value, which is expressed by `()`, the unit type. Therefore, nothing is returned, which contradicts the function definition and results in an error. In this output, Rust provides a message to possibly help rectify this issue: it suggests removing the semicolon, which would fix the error.
programming_docs
rust Programming a Guessing Game Programming a Guessing Game =========================== Let’s jump into Rust by working through a hands-on project together! This chapter introduces you to a few common Rust concepts by showing you how to use them in a real program. You’ll learn about `let`, `match`, methods, associated functions, using external crates, and more! In the following chapters, we’ll explore these ideas in more detail. In this chapter, you’ll practice the fundamentals. We’ll implement a classic beginner programming problem: a guessing game. Here’s how it works: the program will generate a random integer between 1 and 100. It will then prompt the player to enter a guess. After a guess is entered, the program will indicate whether the guess is too low or too high. If the guess is correct, the game will print a congratulatory message and exit. Setting Up a New Project ------------------------ To set up a new project, go to the *projects* directory that you created in Chapter 1 and make a new project using Cargo, like so: ``` $ cargo new guessing_game $ cd guessing_game ``` The first command, `cargo new`, takes the name of the project (`guessing_game`) as the first argument. The second command changes to the new project’s directory. Look at the generated *Cargo.toml* file: Filename: Cargo.toml ``` [package] name = "guessing_game" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] ``` As you saw in Chapter 1, `cargo new` generates a “Hello, world!” program for you. Check out the *src/main.rs* file: Filename: src/main.rs ``` fn main() { println!("Hello, world!"); } ``` Now let’s compile this “Hello, world!” program and run it in the same step using the `cargo run` command: ``` $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 1.50s Running `target/debug/guessing_game` Hello, world! ``` The `run` command comes in handy when you need to rapidly iterate on a project, as we’ll do in this game, quickly testing each iteration before moving on to the next one. Reopen the *src/main.rs* file. You’ll be writing all the code in this file. Processing a Guess ------------------ The first part of the guessing game program will ask for user input, process that input, and check that the input is in the expected form. To start, we’ll allow the player to input a guess. Enter the code in Listing 2-1 into *src/main.rs*. Filename: src/main.rs ``` use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } ``` Listing 2-1: Code that gets a guess from the user and prints it This code contains a lot of information, so let’s go over it line by line. To obtain user input and then print the result as output, we need to bring the `io` input/output library into scope. The `io` library comes from the standard library, known as `std`: ``` use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } ``` By default, Rust has a set of items defined in the standard library that it brings into the scope of every program. This set is called the *prelude*, and you can see everything in it [in the standard library documentation](../std/prelude/index). If a type you want to use isn’t in the prelude, you have to bring that type into scope explicitly with a `use` statement. Using the `std::io` library provides you with a number of useful features, including the ability to accept user input. As you saw in Chapter 1, the `main` function is the entry point into the program: ``` use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } ``` The `fn` syntax declares a new function, the parentheses, `()`, indicate there are no parameters, and the curly bracket, `{`, starts the body of the function. As you also learned in Chapter 1, `println!` is a macro that prints a string to the screen: ``` use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } ``` This code is printing a prompt stating what the game is and requesting input from the user. ### Storing Values with Variables Next, we’ll create a *variable* to store the user input, like this: ``` use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } ``` Now the program is getting interesting! There’s a lot going on in this little line. We use the `let` statement to create the variable. Here’s another example: ``` let apples = 5; ``` This line creates a new variable named `apples` and binds it to the value 5. In Rust, variables are immutable by default, meaning once we give the variable a value, the value won't change. We’ll be discussing this concept in detail in the [“Variables and Mutability”](ch03-01-variables-and-mutability#variables-and-mutability) section in Chapter 3. To make a variable mutable, we add `mut` before the variable name: ``` let apples = 5; // immutable let mut bananas = 5; // mutable ``` > Note: The `//` syntax starts a comment that continues until the end of the line. Rust ignores everything in comments. We’ll discuss comments in more detail in [Chapter 3](ch03-04-comments). > > Returning to the guessing game program, you now know that `let mut guess` will introduce a mutable variable named `guess`. The equal sign (`=`) tells Rust we want to bind something to the variable now. On the right of the equals sign is the value that `guess` is bound to, which is the result of calling `String::new`, a function that returns a new instance of a `String`. [`String`](../std/string/struct.string) is a string type provided by the standard library that is a growable, UTF-8 encoded bit of text. The `::` syntax in the `::new` line indicates that `new` is an associated function of the `String` type. An *associated function* is a function that’s implemented on a type, in this case `String`. This `new` function creates a new, empty string. You’ll find a `new` function on many types, because it’s a common name for a function that makes a new value of some kind. In full, the `let mut guess = String::new();` line has created a mutable variable that is currently bound to a new, empty instance of a `String`. Whew! ### Receiving User Input Recall that we included the input/output functionality from the standard library with `use std::io;` on the first line of the program. Now we’ll call the `stdin` function from the `io` module, which will allow us to handle user input: ``` use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } ``` If we hadn’t imported the `io` library with `use std::io` at the beginning of the program, we could still use the function by writing this function call as `std::io::stdin`. The `stdin` function returns an instance of [`std::io::Stdin`](../std/io/struct.stdin), which is a type that represents a handle to the standard input for your terminal. Next, the line `.read_line(&mut guess)` calls the [`read_line`](../std/io/struct.stdin#method.read_line) method on the standard input handle to get input from the user. We’re also passing `&mut guess` as the argument to `read_line` to tell it what string to store the user input in. The full job of `read_line` is to take whatever the user types into standard input and append that into a string (without overwriting its contents), so we therefore pass that string as an argument. The string argument needs to be mutable so the method can change the string’s content. The `&` indicates that this argument is a *reference*, which gives you a way to let multiple parts of your code access one piece of data without needing to copy that data into memory multiple times. References are a complex feature, and one of Rust’s major advantages is how safe and easy it is to use references. You don’t need to know a lot of those details to finish this program. For now, all you need to know is that like variables, references are immutable by default. Hence, you need to write `&mut guess` rather than `&guess` to make it mutable. (Chapter 4 will explain references more thoroughly.) ### Handling Potential Failure with the `Result` Type We’re still working on this line of code. We’re now discussing a third line of text, but note that it’s still part of a single logical line of code. The next part is this method: ``` use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } ``` We could have written this code as: ``` io::stdin().read_line(&mut guess).expect("Failed to read line"); ``` However, one long line is difficult to read, so it’s best to divide it. It’s often wise to introduce a newline and other whitespace to help break up long lines when you call a method with the `.method_name()` syntax. Now let’s discuss what this line does. As mentioned earlier, `read_line` puts whatever the user enters into the string we pass to it, but it also returns a `Result` value. [`Result`](../std/result/enum.result) is an [*enumeration*](ch06-00-enums), often called an *enum*, which is a type that can be in one of multiple possible states. We call each possible state a *variant*. Chapter 6 will cover enums in more detail. The purpose of these `Result` types is to encode error-handling information. `Result`'s variants are `Ok` and `Err`. The `Ok` variant indicates the operation was successful, and inside `Ok` is the successfully generated value. The `Err` variant means the operation failed, and `Err` contains information about how or why the operation failed. Values of the `Result` type, like values of any type, have methods defined on them. An instance of `Result` has an [`expect` method](../std/result/enum.result#method.expect) that you can call. If this instance of `Result` is an `Err` value, `expect` will cause the program to crash and display the message that you passed as an argument to `expect`. If the `read_line` method returns an `Err`, it would likely be the result of an error coming from the underlying operating system. If this instance of `Result` is an `Ok` value, `expect` will take the return value that `Ok` is holding and return just that value to you so you can use it. In this case, that value is the number of bytes in the user’s input. If you don’t call `expect`, the program will compile, but you’ll get a warning: ``` $ cargo build Compiling guessing_game v0.1.0 (file:///projects/guessing_game) warning: unused `Result` that must be used --> src/main.rs:10:5 | 10 | io::stdin().read_line(&mut guess); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(unused_must_use)]` on by default = note: this `Result` may be an `Err` variant, which should be handled warning: `guessing_game` (bin "guessing_game") generated 1 warning Finished dev [unoptimized + debuginfo] target(s) in 0.59s ``` Rust warns that you haven’t used the `Result` value returned from `read_line`, indicating that the program hasn’t handled a possible error. The right way to suppress the warning is to actually write error handling, but in our case we just want to crash this program when a problem occurs, so we can use `expect`. You’ll learn about recovering from errors in [Chapter 9](ch09-02-recoverable-errors-with-result). ### Printing Values with `println!` Placeholders Aside from the closing curly bracket, there’s only one more line to discuss in the code so far: ``` use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } ``` This line prints the string that now contains the user’s input. The `{}` set of curly brackets is a placeholder: think of `{}` as little crab pincers that hold a value in place. You can print more than one value using curly brackets: the first set of curly brackets holds the first value listed after the format string, the second set holds the second value, and so on. Printing multiple values in one call to `println!` would look like this: ``` #![allow(unused)] fn main() { let x = 5; let y = 10; println!("x = {} and y = {}", x, y); } ``` This code would print `x = 5 and y = 10`. ### Testing the First Part Let’s test the first part of the guessing game. Run it using `cargo run`: ``` $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 6.44s Running `target/debug/guessing_game` Guess the number! Please input your guess. 6 You guessed: 6 ``` At this point, the first part of the game is done: we’re getting input from the keyboard and then printing it. Generating a Secret Number -------------------------- Next, we need to generate a secret number that the user will try to guess. The secret number should be different every time so the game is fun to play more than once. We’ll use a random number between 1 and 100 so the game isn’t too difficult. Rust doesn’t yet include random number functionality in its standard library. However, the Rust team does provide a [`rand` crate](https://crates.io/crates/rand) with said functionality. ### Using a Crate to Get More Functionality Remember that a crate is a collection of Rust source code files. The project we’ve been building is a *binary crate*, which is an executable. The `rand` crate is a *library crate*, which contains code intended to be used in other programs and can't be executed on its own. Cargo’s coordination of external crates is where Cargo really shines. Before we can write code that uses `rand`, we need to modify the *Cargo.toml* file to include the `rand` crate as a dependency. Open that file now and add the following line to the bottom beneath the `[dependencies]` section header that Cargo created for you. Be sure to specify `rand` exactly as we have here, with this version number, or the code examples in this tutorial may not work. Filename: Cargo.toml ``` rand = "0.8.3" ``` In the *Cargo.toml* file, everything that follows a header is part of that section that continues until another section starts. In `[dependencies]` you tell Cargo which external crates your project depends on and which versions of those crates you require. In this case, we specify the `rand` crate with the semantic version specifier `0.8.3`. Cargo understands [Semantic Versioning](http://semver.org) (sometimes called *SemVer*), which is a standard for writing version numbers. The number `0.8.3` is actually shorthand for `^0.8.3`, which means any version that is at least `0.8.3` but below `0.9.0`. Cargo considers these versions to have public APIs compatible with version `0.8.3`, and this specification ensures you’ll get the latest patch release that will still compile with the code in this chapter. Any version `0.9.0` or greater is not guaranteed to have the same API as what the following examples use. Now, without changing any of the code, let’s build the project, as shown in Listing 2-2. ``` $ cargo build Updating crates.io index Downloaded rand v0.8.3 Downloaded libc v0.2.86 Downloaded getrandom v0.2.2 Downloaded cfg-if v1.0.0 Downloaded ppv-lite86 v0.2.10 Downloaded rand_chacha v0.3.0 Downloaded rand_core v0.6.2 Compiling rand_core v0.6.2 Compiling libc v0.2.86 Compiling getrandom v0.2.2 Compiling cfg-if v1.0.0 Compiling ppv-lite86 v0.2.10 Compiling rand_chacha v0.3.0 Compiling rand v0.8.3 Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 2.53s ``` Listing 2-2: The output from running `cargo build` after adding the rand crate as a dependency You may see different version numbers (but they will all be compatible with the code, thanks to SemVer!), different lines (depending on the operating system), and the lines may be in a different order. When we include an external dependency, Cargo fetches the latest versions of everything that dependency needs from the *registry*, which is a copy of data from [Crates.io](https://crates.io/). Crates.io is where people in the Rust ecosystem post their open source Rust projects for others to use. After updating the registry, Cargo checks the `[dependencies]` section and downloads any crates listed that aren’t already downloaded. In this case, although we only listed `rand` as a dependency, Cargo also grabbed other crates that `rand` depends on to work. After downloading the crates, Rust compiles them and then compiles the project with the dependencies available. If you immediately run `cargo build` again without making any changes, you won’t get any output aside from the `Finished` line. Cargo knows it has already downloaded and compiled the dependencies, and you haven’t changed anything about them in your *Cargo.toml* file. Cargo also knows that you haven’t changed anything about your code, so it doesn’t recompile that either. With nothing to do, it simply exits. If you open up the *src/main.rs* file, make a trivial change, and then save it and build again, you’ll only see two lines of output: ``` $ cargo build Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs ``` These lines show Cargo only updates the build with your tiny change to the *src/main.rs* file. Your dependencies haven’t changed, so Cargo knows it can reuse what it has already downloaded and compiled for those. #### Ensuring Reproducible Builds with the *Cargo.lock* File Cargo has a mechanism that ensures you can rebuild the same artifact every time you or anyone else builds your code: Cargo will use only the versions of the dependencies you specified until you indicate otherwise. For example, say that next week version 0.8.4 of the `rand` crate comes out, and that version contains an important bug fix, but it also contains a regression that will break your code. To handle this, Rust creates the *Cargo.lock* file the first time you run `cargo build`, so we now have this in the *guessing\_game* directory. When you build a project for the first time, Cargo figures out all the versions of the dependencies that fit the criteria and then writes them to the *Cargo.lock* file. When you build your project in the future, Cargo will see that the *Cargo.lock* file exists and use the versions specified there rather than doing all the work of figuring out versions again. This lets you have a reproducible build automatically. In other words, your project will remain at `0.8.3` until you explicitly upgrade, thanks to the *Cargo.lock* file. Because the *Cargo.lock* file is important for reproducible builds, it's often checked into source control with the rest of the code in your project. #### Updating a Crate to Get a New Version When you *do* want to update a crate, Cargo provides the command `update`, which will ignore the *Cargo.lock* file and figure out all the latest versions that fit your specifications in *Cargo.toml*. Cargo will then write those versions to the *Cargo.lock* file. Otherwise, by default, Cargo will only look for versions greater than `0.8.3` and less than `0.9.0`. If the `rand` crate has released the two new versions `0.8.4` and `0.9.0` you would see the following if you ran `cargo update`: ``` $ cargo update Updating crates.io index Updating rand v0.8.3 -> v0.8.4 ``` Cargo ignores the `0.9.0` release. At this point, you would also notice a change in your *Cargo.lock* file noting that the version of the `rand` crate you are now using is `0.8.4`. To use `rand` version `0.9.0` or any version in the `0.9.x` series, you’d have to update the *Cargo.toml* file to look like this instead: ``` [dependencies] rand = "0.9.0" ``` The next time you run `cargo build`, Cargo will update the registry of crates available and reevaluate your `rand` requirements according to the new version you have specified. There’s a lot more to say about [Cargo](http://doc.crates.io) and [its ecosystem](http://doc.crates.io/crates-io.html) which we’ll discuss in Chapter 14, but for now, that’s all you need to know. Cargo makes it very easy to reuse libraries, so Rustaceans are able to write smaller projects that are assembled from a number of packages. ### Generating a Random Number Let’s start using `rand` to generate a number to guess. The next step is to update *src/main.rs*, as shown in Listing 2-3. Filename: src/main.rs ``` use std::io; use rand::Rng; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } ``` Listing 2-3: Adding code to generate a random number First, we add the line `use rand::Rng`. The `Rng` trait defines methods that random number generators implement, and this trait must be in scope for us to use those methods. Chapter 10 will cover traits in detail. Next, we’re adding two lines in the middle. In the first line, we call the `rand::thread_rng` function that gives us the particular random number generator that we’re going to use: one that is local to the current thread of execution and seeded by the operating system. Then we call the `gen_range` method on the random number generator. This method is defined by the `Rng` trait that we brought into scope with the `use rand::Rng` statement. The `gen_range` method takes a range expression as an argument and generates a random number in the range. The kind of range expression we’re using here takes the form `start..=end` and is inclusive on the lower and upper bounds, so we need to specify `1..=100` to request a number between 1 and 100. > Note: You won’t just know which traits to use and which methods and functions to call from a crate, so each crate has documentation with instructions for using it. Another neat feature of Cargo is that running the `cargo doc --open` command will build documentation provided by all of your dependencies locally and open it in your browser. If you’re interested in other functionality in the `rand` crate, for example, run `cargo doc --open` and click `rand` in the sidebar on the left. > > The second new line prints the secret number. This is useful while we’re developing the program to be able to test it, but we’ll delete it from the final version. It’s not much of a game if the program prints the answer as soon as it starts! Try running the program a few times: ``` $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 2.53s Running `target/debug/guessing_game` Guess the number! The secret number is: 7 Please input your guess. 4 You guessed: 4 $ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.02s Running `target/debug/guessing_game` Guess the number! The secret number is: 83 Please input your guess. 5 You guessed: 5 ``` You should get different random numbers, and they should all be numbers between 1 and 100. Great job! Comparing the Guess to the Secret Number ---------------------------------------- Now that we have user input and a random number, we can compare them. That step is shown in Listing 2-4. Note that this code won’t compile quite yet, as we will explain. Filename: src/main.rs ``` use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { // --snip-- println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), } } ``` Listing 2-4: Handling the possible return values of comparing two numbers First we add another `use` statement, bringing a type called `std::cmp::Ordering` into scope from the standard library. The `Ordering` type is another enum and has the variants `Less`, `Greater`, and `Equal`. These are the three outcomes that are possible when you compare two values. Then we add five new lines at the bottom that use the `Ordering` type. The `cmp` method compares two values and can be called on anything that can be compared. It takes a reference to whatever you want to compare with: here it’s comparing the `guess` to the `secret_number`. Then it returns a variant of the `Ordering` enum we brought into scope with the `use` statement. We use a [`match`](ch06-02-match) expression to decide what to do next based on which variant of `Ordering` was returned from the call to `cmp` with the values in `guess` and `secret_number`. A `match` expression is made up of *arms*. An arm consists of a *pattern* to match against, and the code that should be run if the value given to `match` fits that arm’s pattern. Rust takes the value given to `match` and looks through each arm’s pattern in turn. Patterns and the `match` construct are powerful Rust features that let you express a variety of situations your code might encounter and make sure that you handle them all. These features will be covered in detail in Chapter 6 and Chapter 18, respectively. Let’s walk through an example with the `match` expression we use here. Say that the user has guessed 50 and the randomly generated secret number this time is 38. When the code compares 50 to 38, the `cmp` method will return `Ordering::Greater`, because 50 is greater than 38. The `match` expression gets the `Ordering::Greater` value and starts checking each arm’s pattern. It looks at the first arm’s pattern, `Ordering::Less`, and sees that the value `Ordering::Greater` does not match `Ordering::Less`, so it ignores the code in that arm and moves to the next arm. The next arm’s pattern is `Ordering::Greater`, which *does* match `Ordering::Greater`! The associated code in that arm will execute and print `Too big!` to the screen. The `match` expression ends after the first successful match, so it won’t look at the last arm in this scenario. However, the code in Listing 2-4 won’t compile yet. Let’s try it: ``` $ cargo build Compiling libc v0.2.86 Compiling getrandom v0.2.2 Compiling cfg-if v1.0.0 Compiling ppv-lite86 v0.2.10 Compiling rand_core v0.6.2 Compiling rand_chacha v0.3.0 Compiling rand v0.8.3 Compiling guessing_game v0.1.0 (file:///projects/guessing_game) error[E0308]: mismatched types --> src/main.rs:22:21 | 22 | match guess.cmp(&secret_number) { | ^^^^^^^^^^^^^^ expected struct `String`, found integer | = note: expected reference `&String` found reference `&{integer}` For more information about this error, try `rustc --explain E0308`. error: could not compile `guessing_game` due to previous error ``` The core of the error states that there are *mismatched types*. Rust has a strong, static type system. However, it also has type inference. When we wrote `let mut guess = String::new()`, Rust was able to infer that `guess` should be a `String` and didn’t make us write the type. The `secret_number`, on the other hand, is a number type. A few of Rust’s number types can have a value between 1 and 100: `i32`, a 32-bit number; `u32`, an unsigned 32-bit number; `i64`, a 64-bit number; as well as others. Unless otherwise specified, Rust defaults to an `i32`, which is the type of `secret_number` unless you add type information elsewhere that would cause Rust to infer a different numerical type. The reason for the error is that Rust cannot compare a string and a number type. Ultimately, we want to convert the `String` the program reads as input into a real number type so we can compare it numerically to the secret number. We do so by adding this line to the `main` function body: Filename: src/main.rs ``` use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); println!("Please input your guess."); // --snip-- let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = guess.trim().parse().expect("Please type a number!"); println!("You guessed: {guess}"); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), } } ``` The line is: ``` let guess: u32 = guess.trim().parse().expect("Please type a number!"); ``` We create a variable named `guess`. But wait, doesn’t the program already have a variable named `guess`? It does, but helpfully Rust allows us to *shadow* the previous value of `guess` with a new one. Shadowing lets us reuse the `guess` variable name rather than forcing us to create two unique variables, such as `guess_str` and `guess` for example. We’ll cover this in more detail in Chapter 3, but for now know that this feature is often used when you want to convert a value from one type to another type. We bind this new variable to the expression `guess.trim().parse()`. The `guess` in the expression refers to the original `guess` variable that contained the input as a string. The `trim` method on a `String` instance will eliminate any whitespace at the beginning and end, which we must do to be able to compare the string to the `u32`, which can only contain numerical data. The user must press enter to satisfy `read_line` and input their guess, which adds a newline character to the string. For example, if the user types 5 and presses enter, `guess` looks like this: `5\n`. The `\n` represents “newline”. (On Windows, pressing enter results in a carriage return and a newline, `\r\n`). The `trim` method eliminates `\n` or `\r\n`, resulting in just `5`. The [`parse` method on strings](../std/primitive.str#method.parse) converts a string to another type. Here, we use it to convert from a string to a number. We need to tell Rust the exact number type we want by using `let guess: u32`. The colon (`:`) after `guess` tells Rust we’ll annotate the variable’s type. Rust has a few built-in number types; the `u32` seen here is an unsigned, 32-bit integer. It’s a good default choice for a small positive number. You’ll learn about other number types in Chapter 3. Additionally, the `u32` annotation in this example program and the comparison with `secret_number` means that Rust will infer that `secret_number` should be a `u32` as well. So now the comparison will be between two values of the same type! The `parse` method will only work on characters that can logically be converted into numbers and so can easily cause errors. If, for example, the string contained `A👍%`, there would be no way to convert that to a number. Because it might fail, the `parse` method returns a `Result` type, much as the `read_line` method does (discussed earlier in [“Handling Potential Failure with the `Result` Type”](#handling-potential-failure-with-the-result-type)). We’ll treat this `Result` the same way by using the `expect` method again. If `parse` returns an `Err` `Result` variant because it couldn’t create a number from the string, the `expect` call will crash the game and print the message we give it. If `parse` can successfully convert the string to a number, it will return the `Ok` variant of `Result`, and `expect` will return the number that we want from the `Ok` value. Let’s run the program now! ``` $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 0.43s Running `target/debug/guessing_game` Guess the number! The secret number is: 58 Please input your guess. 76 You guessed: 76 Too big! ``` Nice! Even though spaces were added before the guess, the program still figured out that the user guessed 76. Run the program a few times to verify the different behavior with different kinds of input: guess the number correctly, guess a number that is too high, and guess a number that is too low. We have most of the game working now, but the user can make only one guess. Let’s change that by adding a loop! Allowing Multiple Guesses with Looping -------------------------------------- The `loop` keyword creates an infinite loop. We’ll add a loop to give users more chances at guessing the number: Filename: src/main.rs ``` use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); // --snip-- println!("The secret number is: {secret_number}"); loop { println!("Please input your guess."); // --snip-- let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = guess.trim().parse().expect("Please type a number!"); println!("You guessed: {guess}"); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), } } } ``` As you can see, we’ve moved everything from the guess input prompt onward into a loop. Be sure to indent the lines inside the loop another four spaces each and run the program again. The program will now ask for another guess forever, which actually introduces a new problem. It doesn’t seem like the user can quit! The user could always interrupt the program by using the keyboard shortcut ctrl-c. But there’s another way to escape this insatiable monster, as mentioned in the `parse` discussion in [“Comparing the Guess to the Secret Number”](#comparing-the-guess-to-the-secret-number): if the user enters a non-number answer, the program will crash. We can take advantage of that to allow the user to quit, as shown here: ``` $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 1.50s Running `target/debug/guessing_game` Guess the number! The secret number is: 59 Please input your guess. 45 You guessed: 45 Too small! Please input your guess. 60 You guessed: 60 Too big! Please input your guess. 59 You guessed: 59 You win! Please input your guess. quit thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidDigit }', src/main.rs:28:47 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` Typing `quit` will quit the game, but as you’ll notice so will entering any other non-number input. This is suboptimal to say the least; we want the game to also stop when the correct number is guessed. ### Quitting After a Correct Guess Let’s program the game to quit when the user wins by adding a `break` statement: Filename: src/main.rs ``` use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = guess.trim().parse().expect("Please type a number!"); println!("You guessed: {guess}"); // --snip-- match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } } ``` Adding the `break` line after `You win!` makes the program exit the loop when the user guesses the secret number correctly. Exiting the loop also means exiting the program, because the loop is the last part of `main`. ### Handling Invalid Input To further refine the game’s behavior, rather than crashing the program when the user inputs a non-number, let’s make the game ignore a non-number so the user can continue guessing. We can do that by altering the line where `guess` is converted from a `String` to a `u32`, as shown in Listing 2-5. Filename: src/main.rs ``` use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); println!("The secret number is: {secret_number}"); loop { println!("Please input your guess."); let mut guess = String::new(); // --snip-- io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("You guessed: {guess}"); // --snip-- match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } } ``` Listing 2-5: Ignoring a non-number guess and asking for another guess instead of crashing the program We switch from an `expect` call to a `match` expression to move from crashing on an error to handling the error. Remember that `parse` returns a `Result` type and `Result` is an enum that has the variants `Ok` and `Err`. We’re using a `match` expression here, as we did with the `Ordering` result of the `cmp` method. If `parse` is able to successfully turn the string into a number, it will return an `Ok` value that contains the resulting number. That `Ok` value will match the first arm’s pattern, and the `match` expression will just return the `num` value that `parse` produced and put inside the `Ok` value. That number will end up right where we want it in the new `guess` variable we’re creating. If `parse` is *not* able to turn the string into a number, it will return an `Err` value that contains more information about the error. The `Err` value does not match the `Ok(num)` pattern in the first `match` arm, but it does match the `Err(_)` pattern in the second arm. The underscore, `_`, is a catchall value; in this example, we’re saying we want to match all `Err` values, no matter what information they have inside them. So the program will execute the second arm’s code, `continue`, which tells the program to go to the next iteration of the `loop` and ask for another guess. So, effectively, the program ignores all errors that `parse` might encounter! Now everything in the program should work as expected. Let’s try it: ``` $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 4.45s Running `target/debug/guessing_game` Guess the number! The secret number is: 61 Please input your guess. 10 You guessed: 10 Too small! Please input your guess. 99 You guessed: 99 Too big! Please input your guess. foo Please input your guess. 61 You guessed: 61 You win! ``` Awesome! With one tiny final tweak, we will finish the guessing game. Recall that the program is still printing the secret number. That worked well for testing, but it ruins the game. Let’s delete the `println!` that outputs the secret number. Listing 2-6 shows the final code. Filename: src/main.rs ``` use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1..=100); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("You guessed: {guess}"); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } } ``` Listing 2-6: Complete guessing game code Summary ------- At this point, you’ve successfully built the guessing game. Congratulations! This project was a hands-on way to introduce you to many new Rust concepts: `let`, `match`, functions, the use of external crates, and more. In the next few chapters, you’ll learn about these concepts in more detail. Chapter 3 covers concepts that most programming languages have, such as variables, data types, and functions, and shows how to use them in Rust. Chapter 4 explores ownership, a feature that makes Rust different from other languages. Chapter 5 discusses structs and method syntax, and Chapter 6 explains how enums work.
programming_docs
rust Test Organization Test Organization ================= As mentioned at the start of the chapter, testing is a complex discipline, and different people use different terminology and organization. The Rust community thinks about tests in terms of two main categories: unit tests and integration tests. *Unit tests* are small and more focused, testing one module in isolation at a time, and can test private interfaces. *Integration tests* are entirely external to your library and use your code in the same way any other external code would, using only the public interface and potentially exercising multiple modules per test. Writing both kinds of tests is important to ensure that the pieces of your library are doing what you expect them to, separately and together. ### Unit Tests The purpose of unit tests is to test each unit of code in isolation from the rest of the code to quickly pinpoint where code is and isn’t working as expected. You’ll put unit tests in the *src* directory in each file with the code that they’re testing. The convention is to create a module named `tests` in each file to contain the test functions and to annotate the module with `cfg(test)`. #### The Tests Module and `#[cfg(test)]` The `#[cfg(test)]` annotation on the tests module tells Rust to compile and run the test code only when you run `cargo test`, not when you run `cargo build`. This saves compile time when you only want to build the library and saves space in the resulting compiled artifact because the tests are not included. You’ll see that because integration tests go in a different directory, they don’t need the `#[cfg(test)]` annotation. However, because unit tests go in the same files as the code, you’ll use `#[cfg(test)]` to specify that they shouldn’t be included in the compiled result. Recall that when we generated the new `adder` project in the first section of this chapter, Cargo generated this code for us: Filename: src/lib.rs ``` #[cfg(test)] mod tests { #[test] fn it_works() { let result = 2 + 2; assert_eq!(result, 4); } } ``` This code is the automatically generated test module. The attribute `cfg` stands for *configuration* and tells Rust that the following item should only be included given a certain configuration option. In this case, the configuration option is `test`, which is provided by Rust for compiling and running tests. By using the `cfg` attribute, Cargo compiles our test code only if we actively run the tests with `cargo test`. This includes any helper functions that might be within this module, in addition to the functions annotated with `#[test]`. #### Testing Private Functions There’s debate within the testing community about whether or not private functions should be tested directly, and other languages make it difficult or impossible to test private functions. Regardless of which testing ideology you adhere to, Rust’s privacy rules do allow you to test private functions. Consider the code in Listing 11-12 with the private function `internal_adder`. Filename: src/lib.rs ``` pub fn add_two(a: i32) -> i32 { internal_adder(a, 2) } fn internal_adder(a: i32, b: i32) -> i32 { a + b } #[cfg(test)] mod tests { use super::*; #[test] fn internal() { assert_eq!(4, internal_adder(2, 2)); } } ``` Listing 11-12: Testing a private function Note that the `internal_adder` function is not marked as `pub`. Tests are just Rust code, and the `tests` module is just another module. As we discussed in the [“Paths for Referring to an Item in the Module Tree”](ch07-03-paths-for-referring-to-an-item-in-the-module-tree) section, items in child modules can use the items in their ancestor modules. In this test, we bring all of the `test` module’s parent’s items into scope with `use super::*`, and then the test can call `internal_adder`. If you don’t think private functions should be tested, there’s nothing in Rust that will compel you to do so. ### Integration Tests In Rust, integration tests are entirely external to your library. They use your library in the same way any other code would, which means they can only call functions that are part of your library’s public API. Their purpose is to test whether many parts of your library work together correctly. Units of code that work correctly on their own could have problems when integrated, so test coverage of the integrated code is important as well. To create integration tests, you first need a *tests* directory. #### The *tests* Directory We create a *tests* directory at the top level of our project directory, next to *src*. Cargo knows to look for integration test files in this directory. We can then make as many test files as we want, and Cargo will compile each of the files as an individual crate. Let’s create an integration test. With the code in Listing 11-12 still in the *src/lib.rs* file, make a *tests* directory, and create a new file named *tests/integration\_test.rs*. Your directory structure should look like this: ``` adder ├── Cargo.lock ├── Cargo.toml ├── src │   └── lib.rs └── tests └── integration_test.rs ``` Enter the code in Listing 11-13 into the *tests/integration\_test.rs* file: Filename: tests/integration\_test.rs ``` use adder; #[test] fn it_adds_two() { assert_eq!(4, adder::add_two(2)); } ``` Listing 11-13: An integration test of a function in the `adder` crate Each file in the `tests` directory is a separate crate, so we need to bring our library into each test crate’s scope. For that reason we add `use adder` at the top of the code, which we didn’t need in the unit tests. We don’t need to annotate any code in *tests/integration\_test.rs* with `#[cfg(test)]`. Cargo treats the `tests` directory specially and compiles files in this directory only when we run `cargo test`. Run `cargo test` now: ``` $ cargo test Compiling adder v0.1.0 (file:///projects/adder) Finished test [unoptimized + debuginfo] target(s) in 1.31s Running unittests src/lib.rs (target/debug/deps/adder-1082c4b063a8fbe6) running 1 test test tests::internal ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Running tests/integration_test.rs (target/debug/deps/integration_test-1082c4b063a8fbe6) running 1 test test it_adds_two ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests adder running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` The three sections of output include the unit tests, the integration test, and the doc tests. Note that if any test in a section fails, the following sections will not be run. For example, if a unit test fails, there won’t be any output for integration and doc tests because those tests will only be run if all unit tests are passing. The first section for the unit tests is the same as we’ve been seeing: one line for each unit test (one named `internal` that we added in Listing 11-12) and then a summary line for the unit tests. The integration tests section starts with the line `Running tests/integration_test.rs`. Next, there is a line for each test function in that integration test and a summary line for the results of the integration test just before the `Doc-tests adder` section starts. Each integration test file has its own section, so if we add more files in the *tests* directory, there will be more integration test sections. We can still run a particular integration test function by specifying the test function’s name as an argument to `cargo test`. To run all the tests in a particular integration test file, use the `--test` argument of `cargo test` followed by the name of the file: ``` $ cargo test --test integration_test Compiling adder v0.1.0 (file:///projects/adder) Finished test [unoptimized + debuginfo] target(s) in 0.64s Running tests/integration_test.rs (target/debug/deps/integration_test-82e7799c1bc62298) running 1 test test it_adds_two ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` This command runs only the tests in the *tests/integration\_test.rs* file. #### Submodules in Integration Tests As you add more integration tests, you might want to make more files in the *tests* directory to help organize them; for example, you can group the test functions by the functionality they’re testing. As mentioned earlier, each file in the *tests* directory is compiled as its own separate crate, which is useful for creating separate scopes to more closely imitate the way end users will be using your crate. However, this means files in the *tests* directory don’t share the same behavior as files in *src* do, as you learned in Chapter 7 regarding how to separate code into modules and files. The different behavior of *tests* directory files is most noticeable when you have a set of helper functions to use in multiple integration test files and you try to follow the steps in the [“Separating Modules into Different Files”](ch07-05-separating-modules-into-different-files) section of Chapter 7 to extract them into a common module. For example, if we create *tests/common.rs* and place a function named `setup` in it, we can add some code to `setup` that we want to call from multiple test functions in multiple test files: Filename: tests/common.rs ``` pub fn setup() { // setup code specific to your library's tests would go here } ``` When we run the tests again, we’ll see a new section in the test output for the *common.rs* file, even though this file doesn’t contain any test functions nor did we call the `setup` function from anywhere: ``` $ cargo test Compiling adder v0.1.0 (file:///projects/adder) Finished test [unoptimized + debuginfo] target(s) in 0.89s Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4) running 1 test test tests::internal ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Running tests/common.rs (target/debug/deps/common-92948b65e88960b4) running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Running tests/integration_test.rs (target/debug/deps/integration_test-92948b65e88960b4) running 1 test test it_adds_two ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests adder running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` Having `common` appear in the test results with `running 0 tests` displayed for it is not what we wanted. We just wanted to share some code with the other integration test files. To avoid having `common` appear in the test output, instead of creating *tests/common.rs*, we’ll create *tests/common/mod.rs*. The project directory now looks like this: ``` ├── Cargo.lock ├── Cargo.toml ├── src │   └── lib.rs └── tests ├── common │   └── mod.rs └── integration_test.rs ``` This is the older naming convention that Rust also understands that we mentioned in the [“Alternate File Paths”](ch07-05-separating-modules-into-different-files#alternate-file-paths) section of Chapter 7. Naming the file this way tells Rust not to treat the `common` module as an integration test file. When we move the `setup` function code into *tests/common/mod.rs* and delete the *tests/common.rs* file, the section in the test output will no longer appear. Files in subdirectories of the *tests* directory don’t get compiled as separate crates or have sections in the test output. After we’ve created *tests/common/mod.rs*, we can use it from any of the integration test files as a module. Here’s an example of calling the `setup` function from the `it_adds_two` test in *tests/integration\_test.rs*: Filename: tests/integration\_test.rs ``` use adder; mod common; #[test] fn it_adds_two() { common::setup(); assert_eq!(4, adder::add_two(2)); } ``` Note that the `mod common;` declaration is the same as the module declaration we demonstrated in Listing 7-21. Then in the test function, we can call the `common::setup()` function. #### Integration Tests for Binary Crates If our project is a binary crate that only contains a *src/main.rs* file and doesn’t have a *src/lib.rs* file, we can’t create integration tests in the *tests* directory and bring functions defined in the *src/main.rs* file into scope with a `use` statement. Only library crates expose functions that other crates can use; binary crates are meant to be run on their own. This is one of the reasons Rust projects that provide a binary have a straightforward *src/main.rs* file that calls logic that lives in the *src/lib.rs* file. Using that structure, integration tests *can* test the library crate with `use` to make the important functionality available. If the important functionality works, the small amount of code in the *src/main.rs* file will work as well, and that small amount of code doesn’t need to be tested. Summary ------- Rust’s testing features provide a way to specify how code should function to ensure it continues to work as you expect, even as you make changes. Unit tests exercise different parts of a library separately and can test private implementation details. Integration tests check that many parts of the library work together correctly, and they use the library’s public API to test the code in the same way external code will use it. Even though Rust’s type system and ownership rules help prevent some kinds of bugs, tests are still important to reduce logic bugs having to do with how your code is expected to behave. Let’s combine the knowledge you learned in this chapter and in previous chapters to work on a project! rust Graceful Shutdown and Cleanup Graceful Shutdown and Cleanup ============================= The code in Listing 20-20 is responding to requests asynchronously through the use of a thread pool, as we intended. We get some warnings about the `workers`, `id`, and `thread` fields that we’re not using in a direct way that reminds us we’re not cleaning up anything. When we use the less elegant ctrl-c method to halt the main thread, all other threads are stopped immediately as well, even if they’re in the middle of serving a request. Next, then, we’ll implement the `Drop` trait to call `join` on each of the threads in the pool so they can finish the requests they’re working on before closing. Then we’ll implement a way to tell the threads they should stop accepting new requests and shut down. To see this code in action, we’ll modify our server to accept only two requests before gracefully shutting down its thread pool. ### Implementing the `Drop` Trait on `ThreadPool` Let’s start with implementing `Drop` on our thread pool. When the pool is dropped, our threads should all join to make sure they finish their work. Listing 20-22 shows a first attempt at a `Drop` implementation; this code won’t quite work yet. Filename: src/lib.rs ``` use std::{ sync::{mpsc, Arc, Mutex}, thread, }; pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Job>, } type Job = Box<dyn FnOnce() + Send + 'static>; impl ThreadPool { /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { workers, sender } } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.send(job).unwrap(); } } impl Drop for ThreadPool { fn drop(&mut self) { for worker in &mut self.workers { println!("Shutting down worker {}", worker.id); worker.thread.join().unwrap(); } } } struct Worker { id: usize, thread: thread::JoinHandle<()>, } impl Worker { fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker { let thread = thread::spawn(move || loop { let job = receiver.lock().unwrap().recv().unwrap(); println!("Worker {id} got a job; executing."); job(); }); Worker { id, thread } } } ``` Listing 20-22: Joining each thread when the thread pool goes out of scope First, we loop through each of the thread pool `workers`. We use `&mut` for this because `self` is a mutable reference, and we also need to be able to mutate `worker`. For each worker, we print a message saying that this particular worker is shutting down, and then we call `join` on that worker’s thread. If the call to `join` fails, we use `unwrap` to make Rust panic and go into an ungraceful shutdown. Here is the error we get when we compile this code: ``` $ cargo check Checking hello v0.1.0 (file:///projects/hello) error[E0507]: cannot move out of `worker.thread` which is behind a mutable reference --> src/lib.rs:52:13 | 52 | worker.thread.join().unwrap(); | ^^^^^^^^^^^^^ ------ `worker.thread` moved due to this method call | | | move occurs because `worker.thread` has type `JoinHandle<()>`, which does not implement the `Copy` trait | note: this function takes ownership of the receiver `self`, which moves `worker.thread` For more information about this error, try `rustc --explain E0507`. error: could not compile `hello` due to previous error ``` The error tells us we can’t call `join` because we only have a mutable borrow of each `worker` and `join` takes ownership of its argument. To solve this issue, we need to move the thread out of the `Worker` instance that owns `thread` so `join` can consume the thread. We did this in Listing 17-15: if `Worker` holds an `Option<thread::JoinHandle<()>>` instead, we can call the `take` method on the `Option` to move the value out of the `Some` variant and leave a `None` variant in its place. In other words, a `Worker` that is running will have a `Some` variant in `thread`, and when we want to clean up a `Worker`, we’ll replace `Some` with `None` so the `Worker` doesn’t have a thread to run. So we know we want to update the definition of `Worker` like this: Filename: src/lib.rs ``` use std::{ sync::{mpsc, Arc, Mutex}, thread, }; pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Job>, } type Job = Box<dyn FnOnce() + Send + 'static>; impl ThreadPool { /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { workers, sender } } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.send(job).unwrap(); } } impl Drop for ThreadPool { fn drop(&mut self) { for worker in &mut self.workers { println!("Shutting down worker {}", worker.id); worker.thread.join().unwrap(); } } } struct Worker { id: usize, thread: Option<thread::JoinHandle<()>>, } impl Worker { fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker { let thread = thread::spawn(move || loop { let job = receiver.lock().unwrap().recv().unwrap(); println!("Worker {id} got a job; executing."); job(); }); Worker { id, thread } } } ``` Now let’s lean on the compiler to find the other places that need to change. Checking this code, we get two errors: ``` $ cargo check Checking hello v0.1.0 (file:///projects/hello) error[E0599]: no method named `join` found for enum `Option` in the current scope --> src/lib.rs:52:27 | 52 | worker.thread.join().unwrap(); | ^^^^ method not found in `Option<JoinHandle<()>>` error[E0308]: mismatched types --> src/lib.rs:72:22 | 72 | Worker { id, thread } | ^^^^^^ expected enum `Option`, found struct `JoinHandle` | = note: expected enum `Option<JoinHandle<()>>` found struct `JoinHandle<_>` help: try wrapping the expression in `Some` | 72 | Worker { id, thread: Some(thread) } | +++++++++++++ + Some errors have detailed explanations: E0308, E0599. For more information about an error, try `rustc --explain E0308`. error: could not compile `hello` due to 2 previous errors ``` Let’s address the second error, which points to the code at the end of `Worker::new`; we need to wrap the `thread` value in `Some` when we create a new `Worker`. Make the following changes to fix this error: Filename: src/lib.rs ``` use std::{ sync::{mpsc, Arc, Mutex}, thread, }; pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Job>, } type Job = Box<dyn FnOnce() + Send + 'static>; impl ThreadPool { /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { workers, sender } } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.send(job).unwrap(); } } impl Drop for ThreadPool { fn drop(&mut self) { for worker in &mut self.workers { println!("Shutting down worker {}", worker.id); worker.thread.join().unwrap(); } } } struct Worker { id: usize, thread: Option<thread::JoinHandle<()>>, } impl Worker { fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker { // --snip-- let thread = thread::spawn(move || loop { let job = receiver.lock().unwrap().recv().unwrap(); println!("Worker {id} got a job; executing."); job(); }); Worker { id, thread: Some(thread), } } } ``` The first error is in our `Drop` implementation. We mentioned earlier that we intended to call `take` on the `Option` value to move `thread` out of `worker`. The following changes will do so: Filename: src/lib.rs ``` use std::{ sync::{mpsc, Arc, Mutex}, thread, }; pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Job>, } type Job = Box<dyn FnOnce() + Send + 'static>; impl ThreadPool { /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { workers, sender } } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.send(job).unwrap(); } } impl Drop for ThreadPool { fn drop(&mut self) { for worker in &mut self.workers { println!("Shutting down worker {}", worker.id); if let Some(thread) = worker.thread.take() { thread.join().unwrap(); } } } } struct Worker { id: usize, thread: Option<thread::JoinHandle<()>>, } impl Worker { fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker { let thread = thread::spawn(move || loop { let job = receiver.lock().unwrap().recv().unwrap(); println!("Worker {id} got a job; executing."); job(); }); Worker { id, thread: Some(thread), } } } ``` As discussed in Chapter 17, the `take` method on `Option` takes the `Some` variant out and leaves `None` in its place. We’re using `if let` to destructure the `Some` and get the thread; then we call `join` on the thread. If a worker’s thread is already `None`, we know that worker has already had its thread cleaned up, so nothing happens in that case. ### Signaling to the Threads to Stop Listening for Jobs With all the changes we’ve made, our code compiles without any warnings. However, the bad news is this code doesn’t function the way we want it to yet. The key is the logic in the closures run by the threads of the `Worker` instances: at the moment, we call `join`, but that won’t shut down the threads because they `loop` forever looking for jobs. If we try to drop our `ThreadPool` with our current implementation of `drop`, the main thread will block forever waiting for the first thread to finish. To fix this problem, we’ll need a change in the `ThreadPool` `drop` implementation and then a change in the `Worker` loop. First, we’ll change the `ThreadPool` `drop` implementation to explicitly drop the `sender` before waiting for the threads to finish. Listing 20-23 shows the changes to `ThreadPool` to explicitly drop `sender`. We use the same `Option` and `take` technique as we did with the thread to be able to move `sender` out of `ThreadPool`: Filename: src/lib.rs ``` use std::{ sync::{mpsc, Arc, Mutex}, thread, }; pub struct ThreadPool { workers: Vec<Worker>, sender: Option<mpsc::Sender<Job>>, } // --snip-- type Job = Box<dyn FnOnce() + Send + 'static>; impl ThreadPool { /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { // --snip-- assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { workers, sender: Some(sender), } } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.as_ref().unwrap().send(job).unwrap(); } } impl Drop for ThreadPool { fn drop(&mut self) { drop(self.sender.take()); for worker in &mut self.workers { println!("Shutting down worker {}", worker.id); if let Some(thread) = worker.thread.take() { thread.join().unwrap(); } } } } struct Worker { id: usize, thread: Option<thread::JoinHandle<()>>, } impl Worker { fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker { let thread = thread::spawn(move || loop { let job = receiver.lock().unwrap().recv().unwrap(); println!("Worker {id} got a job; executing."); job(); }); Worker { id, thread: Some(thread), } } } ``` Listing 20-23: Explicitly drop `sender` before joining the worker threads Dropping `sender` closes the channel, which indicates no more messages will be sent. When that happens, all the calls to `recv` that the workers do in the infinite loop will return an error. In Listing 20-24, we change the `Worker` loop to gracefully exit the loop in that case, which means the threads will finish when the `ThreadPool` `drop` implementation calls `join` on them. Filename: src/lib.rs ``` use std::{ sync::{mpsc, Arc, Mutex}, thread, }; pub struct ThreadPool { workers: Vec<Worker>, sender: Option<mpsc::Sender<Job>>, } type Job = Box<dyn FnOnce() + Send + 'static>; impl ThreadPool { /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { workers, sender: Some(sender), } } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.as_ref().unwrap().send(job).unwrap(); } } impl Drop for ThreadPool { fn drop(&mut self) { drop(self.sender.take()); for worker in &mut self.workers { println!("Shutting down worker {}", worker.id); if let Some(thread) = worker.thread.take() { thread.join().unwrap(); } } } } struct Worker { id: usize, thread: Option<thread::JoinHandle<()>>, } impl Worker { fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker { let thread = thread::spawn(move || loop { let message = receiver.lock().unwrap().recv(); match message { Ok(job) => { println!("Worker {id} got a job; executing."); job(); } Err(_) => { println!("Worker {id} disconnected; shutting down."); break; } } }); Worker { id, thread: Some(thread), } } } ``` Listing 20-24: Explicitly break out of the loop when `recv` returns an error To see this code in action, let’s modify `main` to accept only two requests before gracefully shutting down the server, as shown in Listing 20-25. Filename: src/main.rs ``` use hello::ThreadPool; use std::fs; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; use std::thread; use std::time::Duration; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); let pool = ThreadPool::new(4); for stream in listener.incoming().take(2) { let stream = stream.unwrap(); pool.execute(|| { handle_connection(stream); }); } println!("Shutting down."); } fn handle_connection(mut stream: TcpStream) { let mut buffer = [0; 1024]; stream.read(&mut buffer).unwrap(); let get = b"GET / HTTP/1.1\r\n"; let sleep = b"GET /sleep HTTP/1.1\r\n"; let (status_line, filename) = if buffer.starts_with(get) { ("HTTP/1.1 200 OK", "hello.html") } else if buffer.starts_with(sleep) { thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK", "hello.html") } else { ("HTTP/1.1 404 NOT FOUND", "404.html") }; let contents = fs::read_to_string(filename).unwrap(); let response = format!( "{}\r\nContent-Length: {}\r\n\r\n{}", status_line, contents.len(), contents ); stream.write_all(response.as_bytes()).unwrap(); stream.flush().unwrap(); } ``` Listing 20-25: Shut down the server after serving two requests by exiting the loop You wouldn’t want a real-world web server to shut down after serving only two requests. This code just demonstrates that the graceful shutdown and cleanup is in working order. The `take` method is defined in the `Iterator` trait and limits the iteration to the first two items at most. The `ThreadPool` will go out of scope at the end of `main`, and the `drop` implementation will run. Start the server with `cargo run`, and make three requests. The third request should error, and in your terminal you should see output similar to this: ``` $ cargo run Compiling hello v0.1.0 (file:///projects/hello) Finished dev [unoptimized + debuginfo] target(s) in 1.0s Running `target/debug/hello` Worker 0 got a job; executing. Shutting down. Shutting down worker 0 Worker 3 got a job; executing. Worker 1 disconnected; shutting down. Worker 2 disconnected; shutting down. Worker 3 disconnected; shutting down. Worker 0 disconnected; shutting down. Shutting down worker 1 Shutting down worker 2 Shutting down worker 3 ``` You might see a different ordering of workers and messages printed. We can see how this code works from the messages: workers 0 and 3 got the first two requests. The server stopped accepting connections after the second connection, and the `Drop` implementation on `ThreadPool` starts executing before worker 3 even starts its job. Dropping the `sender` disconnects all the workers and tells them to shut down. The workers each print a message when they disconnect, and then the thread pool calls `join` to wait for each worker thread to finish. Notice one interesting aspect of this particular execution: the `ThreadPool` dropped the `sender`, and before any worker received an error, we tried to join worker 0. Worker 0 had not yet gotten an error from `recv`, so the main thread blocked waiting for worker 0 to finish. In the meantime, worker 3 received a job and then all threads received an error. When worker 0 finished, the main thread waited for the rest of the workers to finish. At that point, they had all exited their loops and stopped. Congrats! We’ve now completed our project; we have a basic web server that uses a thread pool to respond asynchronously. We’re able to perform a graceful shutdown of the server, which cleans up all the threads in the pool. Here’s the full code for reference: Filename: src/main.rs ``` use hello::ThreadPool; use std::fs; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; use std::thread; use std::time::Duration; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); let pool = ThreadPool::new(4); for stream in listener.incoming().take(2) { let stream = stream.unwrap(); pool.execute(|| { handle_connection(stream); }); } println!("Shutting down."); } fn handle_connection(mut stream: TcpStream) { let mut buffer = [0; 1024]; stream.read(&mut buffer).unwrap(); let get = b"GET / HTTP/1.1\r\n"; let sleep = b"GET /sleep HTTP/1.1\r\n"; let (status_line, filename) = if buffer.starts_with(get) { ("HTTP/1.1 200 OK", "hello.html") } else if buffer.starts_with(sleep) { thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK", "hello.html") } else { ("HTTP/1.1 404 NOT FOUND", "404.html") }; let contents = fs::read_to_string(filename).unwrap(); let response = format!( "{}\r\nContent-Length: {}\r\n\r\n{}", status_line, contents.len(), contents ); stream.write_all(response.as_bytes()).unwrap(); stream.flush().unwrap(); } ``` Filename: src/lib.rs ``` use std::{ sync::{mpsc, Arc, Mutex}, thread, }; pub struct ThreadPool { workers: Vec<Worker>, sender: Option<mpsc::Sender<Job>>, } type Job = Box<dyn FnOnce() + Send + 'static>; impl ThreadPool { /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero. pub fn new(size: usize) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { workers, sender: Some(sender), } } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.as_ref().unwrap().send(job).unwrap(); } } impl Drop for ThreadPool { fn drop(&mut self) { drop(self.sender.take()); for worker in &mut self.workers { println!("Shutting down worker {}", worker.id); if let Some(thread) = worker.thread.take() { thread.join().unwrap(); } } } } struct Worker { id: usize, thread: Option<thread::JoinHandle<()>>, } impl Worker { fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker { let thread = thread::spawn(move || loop { let message = receiver.lock().unwrap().recv(); match message { Ok(job) => { println!("Worker {id} got a job; executing."); job(); } Err(_) => { println!("Worker {id} disconnected; shutting down."); break; } } }); Worker { id, thread: Some(thread), } } } ``` We could do more here! If you want to continue enhancing this project, here are some ideas: * Add more documentation to `ThreadPool` and its public methods. * Add tests of the library’s functionality. * Change calls to `unwrap` to more robust error handling. * Use `ThreadPool` to perform some task other than serving web requests. * Find a thread pool crate on [crates.io](https://crates.io/) and implement a similar web server using the crate instead. Then compare its API and robustness to the thread pool we implemented. Summary ------- Well done! You’ve made it to the end of the book! We want to thank you for joining us on this tour of Rust. You’re now ready to implement your own Rust projects and help with other peoples’ projects. Keep in mind that there is a welcoming community of other Rustaceans who would love to help you with any challenges you encounter on your Rust journey.
programming_docs
rust An I/O Project: Building a Command Line Program An I/O Project: Building a Command Line Program =============================================== This chapter is a recap of the many skills you’ve learned so far and an exploration of a few more standard library features. We’ll build a command line tool that interacts with file and command line input/output to practice some of the Rust concepts you now have under your belt. Rust’s speed, safety, single binary output, and cross-platform support make it an ideal language for creating command line tools, so for our project, we’ll make our own version of the classic command line search tool `grep` (**g**lobally search a **r**egular **e**xpression and **p**rint). In the simplest use case, `grep` searches a specified file for a specified string. To do so, `grep` takes as its arguments a file path and a string. Then it reads the file, finds lines in that file that contain the string argument, and prints those lines. Along the way, we’ll show how to make our command line tool use the terminal features that many other command line tools use. We’ll read the value of an environment variable to allow the user to configure the behavior of our tool. We’ll also print error messages to the standard error console stream (`stderr`) instead of standard output (`stdout`), so, for example, the user can redirect successful output to a file while still seeing error messages onscreen. One Rust community member, Andrew Gallant, has already created a fully featured, very fast version of `grep`, called `ripgrep`. By comparison, our version will be fairly simple, but this chapter will give you some of the background knowledge you need to understand a real-world project such as `ripgrep`. Our `grep` project will combine a number of concepts you’ve learned so far: * Organizing code (using what you learned about modules in [Chapter 7](ch07-00-managing-growing-projects-with-packages-crates-and-modules)) * Using vectors and strings (collections, [Chapter 8](ch08-00-common-collections)) * Handling errors ([Chapter 9](ch09-00-error-handling)) * Using traits and lifetimes where appropriate ([Chapter 10](ch10-00-generics)) * Writing tests ([Chapter 11](ch11-00-testing)) We’ll also briefly introduce closures, iterators, and trait objects, which Chapters [13](ch13-00-functional-features) and [17](ch17-00-oop) will cover in detail. rust Enums and Pattern Matching Enums and Pattern Matching ========================== In this chapter we’ll look at *enumerations*, also referred to as *enums*. Enums allow you to define a type by enumerating its possible *variants*. First, we’ll define and use an enum to show how an enum can encode meaning along with data. Next, we’ll explore a particularly useful enum, called `Option`, which expresses that a value can be either something or nothing. Then we’ll look at how pattern matching in the `match` expression makes it easy to run different code for different values of an enum. Finally, we’ll cover how the `if let` construct is another convenient and concise idiom available to handle enums in your code. rust Generic Types, Traits, and Lifetimes Generic Types, Traits, and Lifetimes ==================================== Every programming language has tools for effectively handling the duplication of concepts. In Rust, one such tool is *generics*: abstract stand-ins for concrete types or other properties. We can express the behavior of generics or how they relate to other generics without knowing what will be in their place when compiling and running the code. Functions can take parameters of some generic type, instead of a concrete type like `i32` or `String`, in the same way a function takes parameters with unknown values to run the same code on multiple concrete values. In fact, we’ve already used generics in Chapter 6 with `Option<T>`, Chapter 8 with `Vec<T>` and `HashMap<K, V>`, and Chapter 9 with `Result<T, E>`. In this chapter, you’ll explore how to define your own types, functions, and methods with generics! First, we’ll review how to extract a function to reduce code duplication. We’ll then use the same technique to make a generic function from two functions that differ only in the types of their parameters. We’ll also explain how to use generic types in struct and enum definitions. Then you’ll learn how to use *traits* to define behavior in a generic way. You can combine traits with generic types to constrain a generic type to accept only those types that have a particular behavior, as opposed to just any type. Finally, we’ll discuss *lifetimes*: a variety of generics that give the compiler information about how references relate to each other. Lifetimes allow us to give the compiler enough information about borrowed values so that it can ensure references will be valid in more situations than it could without our help. Removing Duplication by Extracting a Function --------------------------------------------- Generics allow us to replace specific types with a placeholder that represents multiple types to remove code duplication. Before diving into generics syntax, then, let’s first look at how to remove duplication in a way that doesn’t involve generic types by extracting a function that replaces specific values with a placeholder that represents multiple values. Then we’ll apply the same technique to extract a generic function! By looking at how to recognize duplicated code you can extract into a function, you’ll start to recognize duplicated code that can use generics. We begin with the short program in Listing 10-1 that finds the largest number in a list. Filename: src/main.rs ``` fn main() { let number_list = vec![34, 50, 25, 100, 65]; let mut largest = &number_list[0]; for number in &number_list { if number > largest { largest = number; } } println!("The largest number is {}", largest); assert_eq!(*largest, 100); } ``` Listing 10-1: Finding the largest number in a list of numbers We store a list of integers in the variable `number_list` and place a reference to the first number in the list in a variable named `largest`. We then iterate through all the numbers in the list, and if the current number is greater than the number stored in `largest`, replace the reference in that variable. However, if the current number is less than or equal to the largest number seen so far, the variable doesn’t change, and the code moves on to the next number in the list. After considering all the numbers in the list, `largest` should refer to the largest number, which in this case is 100. We've now been tasked with finding the largest number in two different lists of numbers. To do so, we can choose to duplicate the code in Listing 10-1 and use the same logic at two different places in the program, as shown in Listing 10-2. Filename: src/main.rs ``` fn main() { let number_list = vec![34, 50, 25, 100, 65]; let mut largest = &number_list[0]; for number in &number_list { if number > largest { largest = number; } } println!("The largest number is {}", largest); let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; let mut largest = &number_list[0]; for number in &number_list { if number > largest { largest = number; } } println!("The largest number is {}", largest); } ``` Listing 10-2: Code to find the largest number in *two* lists of numbers Although this code works, duplicating code is tedious and error prone. We also have to remember to update the code in multiple places when we want to change it. To eliminate this duplication, we’ll create an abstraction by defining a function that operates on any list of integers passed in a parameter. This solution makes our code clearer and lets us express the concept of finding the largest number in a list abstractly. In Listing 10-3, we extract the code that finds the largest number into a function named `largest`. Then we call the function to find the largest number in the two lists from Listing 10-2. We could also use the function on any other list of `i32` values we might have in the future. Filename: src/main.rs ``` fn largest(list: &[i32]) -> &i32 { let mut largest = &list[0]; for item in list { if item > largest { largest = item; } } largest } fn main() { let number_list = vec![34, 50, 25, 100, 65]; let result = largest(&number_list); println!("The largest number is {}", result); assert_eq!(*result, 100); let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; let result = largest(&number_list); println!("The largest number is {}", result); assert_eq!(*result, 6000); } ``` Listing 10-3: Abstracted code to find the largest number in two lists The `largest` function has a parameter called `list`, which represents any concrete slice of `i32` values we might pass into the function. As a result, when we call the function, the code runs on the specific values that we pass in. In summary, here are the steps we took to change the code from Listing 10-2 to Listing 10-3: 1. Identify duplicate code. 2. Extract the duplicate code into the body of the function and specify the inputs and return values of that code in the function signature. 3. Update the two instances of duplicated code to call the function instead. Next, we’ll use these same steps with generics to reduce code duplication. In the same way that the function body can operate on an abstract `list` instead of specific values, generics allow code to operate on abstract types. For example, say we had two functions: one that finds the largest item in a slice of `i32` values and one that finds the largest item in a slice of `char` values. How would we eliminate that duplication? Let’s find out! rust Defining Modules to Control Scope and Privacy Defining Modules to Control Scope and Privacy ============================================= In this section, we’ll talk about modules and other parts of the module system, namely *paths* that allow you to name items; the `use` keyword that brings a path into scope; and the `pub` keyword to make items public. We’ll also discuss the `as` keyword, external packages, and the glob operator. First, we’re going to start with a list of rules for easy reference when you’re organizing your code in the future. Then we’ll explain each of the rules in detail. ### Modules Cheat Sheet Here we provide a quick reference on how modules, paths, the `use` keyword, and the `pub` keyword work in the compiler, and how most developers organize their code. We’ll be going through examples of each of these rules throughout this chapter, but this is a great place to refer to as a reminder of how modules work. * **Start from the crate root**: When compiling a crate, the compiler first looks in the crate root file (usually *src/lib.rs* for a library crate or *src/main.rs* for a binary crate) for code to compile. * **Declaring modules**: In the crate root file, you can declare new modules; say, you declare a “garden” module with `mod garden;`. The compiler will look for the module’s code in these places: + Inline, within curly brackets that replace the semicolon following `mod garden` + In the file *src/garden.rs* + In the file *src/garden/mod.rs* * **Declaring submodules**: In any file other than the crate root, you can declare submodules. For example, you might declare `mod vegetables;` in *src/garden.rs*. The compiler will look for the submodule’s code within the directory named for the parent module in these places: + Inline, directly following `mod vegetables`, within curly brackets instead of the semicolon + In the file *src/garden/vegetables.rs* + In the file *src/garden/vegetables/mod.rs* * **Paths to code in modules**: Once a module is part of your crate, you can refer to code in that module from anywhere else in that same crate, as long as the privacy rules allow, using the path to the code. For example, an `Asparagus` type in the garden vegetables module would be found at `crate::garden::vegetables::Asparagus`. * **Private vs public**: Code within a module is private from its parent modules by default. To make a module public, declare it with `pub mod` instead of `mod`. To make items within a public module public as well, use `pub` before their declarations. * **The `use` keyword**: Within a scope, the `use` keyword creates shortcuts to items to reduce repetition of long paths. In any scope that can refer to `crate::garden::vegetables::Asparagus`, you can create a shortcut with `use crate::garden::vegetables::Asparagus;` and from then on you only need to write `Asparagus` to make use of that type in the scope. Here we create a binary crate named `backyard` that illustrates these rules. The crate’s directory, also named `backyard`, contains these files and directories: ``` backyard ├── Cargo.lock ├── Cargo.toml └── src ├── garden │   └── vegetables.rs ├── garden.rs └── main.rs ``` The crate root file in this case is *src/main.rs*, and it contains: Filename: src/main.rs ``` use crate::garden::vegetables::Asparagus; pub mod garden; fn main() { let plant = Asparagus {}; println!("I'm growing {:?}!", plant); } ``` The `pub mod garden;` line tells the compiler to include the code it finds in *src/garden.rs*, which is: Filename: src/garden.rs ``` pub mod vegetables; ``` Here, `pub mod vegetables;` means the code in *src/garden/vegetables.rs* is included too. That code is: ``` #[derive(Debug)] pub struct Asparagus {} ``` Now let’s get into the details of these rules and demonstrate them in action! ### Grouping Related Code in Modules *Modules* let us organize code within a crate for readability and easy reuse. Modules also allow us to control the *privacy* of items, because code within a module is private by default. Private items are internal implementation details not available for outside use. We can choose to make modules and the items within them public, which exposes them to allow external code to use and depend on them. As an example, let’s write a library crate that provides the functionality of a restaurant. We’ll define the signatures of functions but leave their bodies empty to concentrate on the organization of the code, rather than the implementation of a restaurant. In the restaurant industry, some parts of a restaurant are referred to as *front of house* and others as *back of house*. Front of house is where customers are; this encompasses where the hosts seat customers, servers take orders and payment, and bartenders make drinks. Back of house is where the chefs and cooks work in the kitchen, dishwashers clean up, and managers do administrative work. To structure our crate in this way, we can organize its functions into nested modules. Create a new library named `restaurant` by running `cargo new restaurant --lib`; then enter the code in Listing 7-1 into *src/lib.rs* to define some modules and function signatures. Here’s the front of house section: Filename: src/lib.rs ``` mod front_of_house { mod hosting { fn add_to_waitlist() {} fn seat_at_table() {} } mod serving { fn take_order() {} fn serve_order() {} fn take_payment() {} } } ``` Listing 7-1: A `front_of_house` module containing other modules that then contain functions We define a module with the `mod` keyword followed by the name of the module (in this case, `front_of_house`). The body of the module then goes inside curly brackets. Inside modules, we can place other modules, as in this case with the modules `hosting` and `serving`. Modules can also hold definitions for other items, such as structs, enums, constants, traits, and—as in Listing 7-1—functions. By using modules, we can group related definitions together and name why they’re related. Programmers using this code can navigate the code based on the groups rather than having to read through all the definitions, making it easier to find the definitions relevant to them. Programmers adding new functionality to this code would know where to place the code to keep the program organized. Earlier, we mentioned that *src/main.rs* and *src/lib.rs* are called crate roots. The reason for their name is that the contents of either of these two files form a module named `crate` at the root of the crate’s module structure, known as the *module tree*. Listing 7-2 shows the module tree for the structure in Listing 7-1. ``` crate └── front_of_house ├── hosting │ ├── add_to_waitlist │ └── seat_at_table └── serving ├── take_order ├── serve_order └── take_payment ``` Listing 7-2: The module tree for the code in Listing 7-1 This tree shows how some of the modules nest inside one another; for example, `hosting` nests inside `front_of_house`. The tree also shows that some modules are *siblings* to each other, meaning they’re defined in the same module; `hosting` and `serving` are siblings defined within `front_of_house`. If module A is contained inside module B, we say that module A is the *child* of module B and that module B is the *parent* of module A. Notice that the entire module tree is rooted under the implicit module named `crate`. The module tree might remind you of the filesystem’s directory tree on your computer; this is a very apt comparison! Just like directories in a filesystem, you use modules to organize your code. And just like files in a directory, we need a way to find our modules. rust Appendix F: Translations of the Book Appendix F: Translations of the Book ==================================== For resources in languages other than English. Most are still in progress; see [the Translations label](https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations) to help or let us know about a new translation! * [Português](https://github.com/rust-br/rust-book-pt-br) (BR) * [Português](https://github.com/nunojesus/rust-book-pt-pt) (PT) * [简体中文](https://github.com/KaiserY/trpl-zh-cn) * [正體中文](https://github.com/rust-tw/book-tw) * [Українська](https://github.com/pavloslav/rust-book-uk-ua) * [Español](https://github.com/thecodix/book), [alternate](https://github.com/ManRR/rust-book-es) * [Italiano](https://github.com/Ciro-Fusco/book_it) * [Русский](https://github.com/rust-lang-ru/book) * [한국어](https://github.com/rinthel/rust-lang-book-ko) * [日本語](https://github.com/rust-lang-ja/book-ja) * [Français](https://github.com/Jimskapt/rust-book-fr) * [Polski](https://github.com/paytchoo/book-pl) * [Cebuano](https://github.com/agentzero1/book) * [Tagalog](https://github.com/josephace135/book) * [Esperanto](https://github.com/psychoslave/Rust-libro) * [ελληνική](https://github.com/TChatzigiannakis/rust-book-greek) * [Svenska](https://github.com/sebras/book) * [Farsi](https://github.com/pomokhtari/rust-book-fa) * [Deutsch](https://github.com/rust-lang-de/rustbook-de) * [Turkish](https://github.com/RustDili/dokuman/tree/master/ceviriler), [online](https://rustdili.github.io/) * [हिंदी](https://github.com/venkatarun95/rust-book-hindi) * [ไทย](https://github.com/rust-lang-th/book-th) * [Danske](https://github.com/DanKHansen/book-dk) rust Reading a File Reading a File ============== Now we’ll add functionality to read the file specified in the `file_path` argument. First, we need a sample file to test it with: we’ll use a file with a small amount of text over multiple lines with some repeated words. Listing 12-3 has an Emily Dickinson poem that will work well! Create a file called *poem.txt* at the root level of your project, and enter the poem “I’m Nobody! Who are you?” Filename: poem.txt ``` I'm nobody! Who are you? Are you nobody, too? Then there's a pair of us - don't tell! They'd banish us, you know. How dreary to be somebody! How public, like a frog To tell your name the livelong day To an admiring bog! ``` Listing 12-3: A poem by Emily Dickinson makes a good test case With the text in place, edit *src/main.rs* and add code to read the file, as shown in Listing 12-4. Filename: src/main.rs ``` use std::env; use std::fs; fn main() { // --snip-- let args: Vec<String> = env::args().collect(); let query = &args[1]; let file_path = &args[2]; println!("Searching for {}", query); println!("In file {}", file_path); let contents = fs::read_to_string(file_path) .expect("Should have been able to read the file"); println!("With text:\n{contents}"); } ``` Listing 12-4: Reading the contents of the file specified by the second argument First, we bring in a relevant part of the standard library with a `use` statement: we need `std::fs` to handle files. In `main`, the new statement `fs::read_to_string` takes the `file_path`, opens that file, and returns a `std::io::Result<String>` of the file’s contents. After that, we again add a temporary `println!` statement that prints the value of `contents` after the file is read, so we can check that the program is working so far. Let’s run this code with any string as the first command line argument (because we haven’t implemented the searching part yet) and the *poem.txt* file as the second argument: ``` $ cargo run -- the poem.txt Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished dev [unoptimized + debuginfo] target(s) in 0.0s Running `target/debug/minigrep the poem.txt` Searching for the In file poem.txt With text: I'm nobody! Who are you? Are you nobody, too? Then there's a pair of us - don't tell! They'd banish us, you know. How dreary to be somebody! How public, like a frog To tell your name the livelong day To an admiring bog! ``` Great! The code read and then printed the contents of the file. But the code has a few flaws. At the moment, the `main` function has multiple responsibilities: generally, functions are clearer and easier to maintain if each function is responsible for only one idea. The other problem is that we’re not handling errors as well as we could. The program is still small, so these flaws aren’t a big problem, but as the program grows, it will be harder to fix them cleanly. It’s good practice to begin refactoring early on when developing a program, because it’s much easier to refactor smaller amounts of code. We’ll do that next.
programming_docs
rust Customizing Builds with Release Profiles Customizing Builds with Release Profiles ======================================== In Rust, *release profiles* are predefined and customizable profiles with different configurations that allow a programmer to have more control over various options for compiling code. Each profile is configured independently of the others. Cargo has two main profiles: the `dev` profile Cargo uses when you run `cargo build` and the `release` profile Cargo uses when you run `cargo build --release`. The `dev` profile is defined with good defaults for development, and the `release` profile has good defaults for release builds. These profile names might be familiar from the output of your builds: ``` $ cargo build Finished dev [unoptimized + debuginfo] target(s) in 0.0s $ cargo build --release Finished release [optimized] target(s) in 0.0s ``` The `dev` and `release` are these different profiles used by the compiler. Cargo has default settings for each of the profiles that apply when you haven't explicitly added any `[profile.*]` sections in the project’s *Cargo.toml* file. By adding `[profile.*]` sections for any profile you want to customize, you override any subset of the default settings. For example, here are the default values for the `opt-level` setting for the `dev` and `release` profiles: Filename: Cargo.toml ``` [profile.dev] opt-level = 0 [profile.release] opt-level = 3 ``` The `opt-level` setting controls the number of optimizations Rust will apply to your code, with a range of 0 to 3. Applying more optimizations extends compiling time, so if you’re in development and compiling your code often, you’ll want fewer optimizations to compile faster even if the resulting code runs slower. The default `opt-level` for `dev` is therefore `0`. When you’re ready to release your code, it’s best to spend more time compiling. You’ll only compile in release mode once, but you’ll run the compiled program many times, so release mode trades longer compile time for code that runs faster. That is why the default `opt-level` for the `release` profile is `3`. You can override a default setting by adding a different value for it in *Cargo.toml*. For example, if we want to use optimization level 1 in the development profile, we can add these two lines to our project’s *Cargo.toml* file: Filename: Cargo.toml ``` [profile.dev] opt-level = 1 ``` This code overrides the default setting of `0`. Now when we run `cargo build`, Cargo will use the defaults for the `dev` profile plus our customization to `opt-level`. Because we set `opt-level` to `1`, Cargo will apply more optimizations than the default, but not as many as in a release build. For the full list of configuration options and defaults for each profile, see [Cargo’s documentation](https://doc.rust-lang.org/cargo/reference/profiles.html). rust Treating Smart Pointers Like Regular References with the Deref Trait Treating Smart Pointers Like Regular References with the `Deref` Trait ====================================================================== Implementing the `Deref` trait allows you to customize the behavior of the *dereference operator* `*` (not to be confused with the multiplication or glob operator). By implementing `Deref` in such a way that a smart pointer can be treated like a regular reference, you can write code that operates on references and use that code with smart pointers too. Let’s first look at how the dereference operator works with regular references. Then we’ll try to define a custom type that behaves like `Box<T>`, and see why the dereference operator doesn’t work like a reference on our newly defined type. We’ll explore how implementing the `Deref` trait makes it possible for smart pointers to work in ways similar to references. Then we’ll look at Rust’s *deref coercion* feature and how it lets us work with either references or smart pointers. > Note: there’s one big difference between the `MyBox<T>` type we’re about to build and the real `Box<T>`: our version will not store its data on the heap. We are focusing this example on `Deref`, so where the data is actually stored is less important than the pointer-like behavior. > > ### Following the Pointer to the Value A regular reference is a type of pointer, and one way to think of a pointer is as an arrow to a value stored somewhere else. In Listing 15-6, we create a reference to an `i32` value and then use the dereference operator to follow the reference to the value: Filename: src/main.rs ``` fn main() { let x = 5; let y = &x; assert_eq!(5, x); assert_eq!(5, *y); } ``` Listing 15-6: Using the dereference operator to follow a reference to an `i32` value The variable `x` holds an `i32` value `5`. We set `y` equal to a reference to `x`. We can assert that `x` is equal to `5`. However, if we want to make an assertion about the value in `y`, we have to use `*y` to follow the reference to the value it’s pointing to (hence *dereference*) so the compiler can compare the actual value. Once we dereference `y`, we have access to the integer value `y` is pointing to that we can compare with `5`. If we tried to write `assert_eq!(5, y);` instead, we would get this compilation error: ``` $ cargo run Compiling deref-example v0.1.0 (file:///projects/deref-example) error[E0277]: can't compare `{integer}` with `&{integer}` --> src/main.rs:6:5 | 6 | assert_eq!(5, y); | ^^^^^^^^^^^^^^^^ no implementation for `{integer} == &{integer}` | = help: the trait `PartialEq<&{integer}>` is not implemented for `{integer}` = help: the following other types implement trait `PartialEq<Rhs>`: f32 f64 i128 i16 i32 i64 i8 isize and 6 others = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info) For more information about this error, try `rustc --explain E0277`. error: could not compile `deref-example` due to previous error ``` Comparing a number and a reference to a number isn’t allowed because they’re different types. We must use the dereference operator to follow the reference to the value it’s pointing to. ### Using `Box<T>` Like a Reference We can rewrite the code in Listing 15-6 to use a `Box<T>` instead of a reference; the dereference operator used on the `Box<T>` in Listing 15-7 functions in the same way as the dereference operator used on the reference in Listing 15-6: Filename: src/main.rs ``` fn main() { let x = 5; let y = Box::new(x); assert_eq!(5, x); assert_eq!(5, *y); } ``` Listing 15-7: Using the dereference operator on a `Box<i32>` The main difference between Listing 15-7 and Listing 15-6 is that here we set `y` to be an instance of a box pointing to a copied value of `x` rather than a reference pointing to the value of `x`. In the last assertion, we can use the dereference operator to follow the box’s pointer in the same way that we did when `y` was a reference. Next, we’ll explore what is special about `Box<T>` that enables us to use the dereference operator by defining our own box type. ### Defining Our Own Smart Pointer Let’s build a smart pointer similar to the `Box<T>` type provided by the standard library to experience how smart pointers behave differently from references by default. Then we’ll look at how to add the ability to use the dereference operator. The `Box<T>` type is ultimately defined as a tuple struct with one element, so Listing 15-8 defines a `MyBox<T>` type in the same way. We’ll also define a `new` function to match the `new` function defined on `Box<T>`. Filename: src/main.rs ``` struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } fn main() {} ``` Listing 15-8: Defining a `MyBox<T>` type We define a struct named `MyBox` and declare a generic parameter `T`, because we want our type to hold values of any type. The `MyBox` type is a tuple struct with one element of type `T`. The `MyBox::new` function takes one parameter of type `T` and returns a `MyBox` instance that holds the value passed in. Let’s try adding the `main` function in Listing 15-7 to Listing 15-8 and changing it to use the `MyBox<T>` type we’ve defined instead of `Box<T>`. The code in Listing 15-9 won’t compile because Rust doesn’t know how to dereference `MyBox`. Filename: src/main.rs ``` struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } fn main() { let x = 5; let y = MyBox::new(x); assert_eq!(5, x); assert_eq!(5, *y); } ``` Listing 15-9: Attempting to use `MyBox<T>` in the same way we used references and `Box<T>` Here’s the resulting compilation error: ``` $ cargo run Compiling deref-example v0.1.0 (file:///projects/deref-example) error[E0614]: type `MyBox<{integer}>` cannot be dereferenced --> src/main.rs:14:19 | 14 | assert_eq!(5, *y); | ^^ For more information about this error, try `rustc --explain E0614`. error: could not compile `deref-example` due to previous error ``` Our `MyBox<T>` type can’t be dereferenced because we haven’t implemented that ability on our type. To enable dereferencing with the `*` operator, we implement the `Deref` trait. ### Treating a Type Like a Reference by Implementing the `Deref` Trait As discussed in the [“Implementing a Trait on a Type”](ch10-02-traits#implementing-a-trait-on-a-type) section of Chapter 10, to implement a trait, we need to provide implementations for the trait’s required methods. The `Deref` trait, provided by the standard library, requires us to implement one method named `deref` that borrows `self` and returns a reference to the inner data. Listing 15-10 contains an implementation of `Deref` to add to the definition of `MyBox`: Filename: src/main.rs ``` use std::ops::Deref; impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } fn main() { let x = 5; let y = MyBox::new(x); assert_eq!(5, x); assert_eq!(5, *y); } ``` Listing 15-10: Implementing `Deref` on `MyBox<T>` The `type Target = T;` syntax defines an associated type for the `Deref` trait to use. Associated types are a slightly different way of declaring a generic parameter, but you don’t need to worry about them for now; we’ll cover them in more detail in Chapter 19. We fill in the body of the `deref` method with `&self.0` so `deref` returns a reference to the value we want to access with the `*` operator; recall from the [“Using Tuple Structs without Named Fields to Create Different Types”](ch05-01-defining-structs#using-tuple-structs-without-named-fields-to-create-different-types) section of Chapter 5 that `.0` accesses the first value in a tuple struct. The `main` function in Listing 15-9 that calls `*` on the `MyBox<T>` value now compiles, and the assertions pass! Without the `Deref` trait, the compiler can only dereference `&` references. The `deref` method gives the compiler the ability to take a value of any type that implements `Deref` and call the `deref` method to get a `&` reference that it knows how to dereference. When we entered `*y` in Listing 15-9, behind the scenes Rust actually ran this code: ``` *(y.deref()) ``` Rust substitutes the `*` operator with a call to the `deref` method and then a plain dereference so we don’t have to think about whether or not we need to call the `deref` method. This Rust feature lets us write code that functions identically whether we have a regular reference or a type that implements `Deref`. The reason the `deref` method returns a reference to a value, and that the plain dereference outside the parentheses in `*(y.deref())` is still necessary, is to do with the ownership system. If the `deref` method returned the value directly instead of a reference to the value, the value would be moved out of `self`. We don’t want to take ownership of the inner value inside `MyBox<T>` in this case or in most cases where we use the dereference operator. Note that the `*` operator is replaced with a call to the `deref` method and then a call to the `*` operator just once, each time we use a `*` in our code. Because the substitution of the `*` operator does not recurse infinitely, we end up with data of type `i32`, which matches the `5` in `assert_eq!` in Listing 15-9. ### Implicit Deref Coercions with Functions and Methods *Deref coercion* converts a reference to a type that implements the `Deref` trait into a reference to another type. For example, deref coercion can convert `&String` to `&str` because `String` implements the `Deref` trait such that it returns `&str`. Deref coercion is a convenience Rust performs on arguments to functions and methods, and works only on types that implement the `Deref` trait. It happens automatically when we pass a reference to a particular type’s value as an argument to a function or method that doesn’t match the parameter type in the function or method definition. A sequence of calls to the `deref` method converts the type we provided into the type the parameter needs. Deref coercion was added to Rust so that programmers writing function and method calls don’t need to add as many explicit references and dereferences with `&` and `*`. The deref coercion feature also lets us write more code that can work for either references or smart pointers. To see deref coercion in action, let’s use the `MyBox<T>` type we defined in Listing 15-8 as well as the implementation of `Deref` that we added in Listing 15-10. Listing 15-11 shows the definition of a function that has a string slice parameter: Filename: src/main.rs ``` fn hello(name: &str) { println!("Hello, {name}!"); } fn main() {} ``` Listing 15-11: A `hello` function that has the parameter `name` of type `&str` We can call the `hello` function with a string slice as an argument, such as `hello("Rust");` for example. Deref coercion makes it possible to call `hello` with a reference to a value of type `MyBox<String>`, as shown in Listing 15-12: Filename: src/main.rs ``` use std::ops::Deref; impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } fn hello(name: &str) { println!("Hello, {name}!"); } fn main() { let m = MyBox::new(String::from("Rust")); hello(&m); } ``` Listing 15-12: Calling `hello` with a reference to a `MyBox<String>` value, which works because of deref coercion Here we’re calling the `hello` function with the argument `&m`, which is a reference to a `MyBox<String>` value. Because we implemented the `Deref` trait on `MyBox<T>` in Listing 15-10, Rust can turn `&MyBox<String>` into `&String` by calling `deref`. The standard library provides an implementation of `Deref` on `String` that returns a string slice, and this is in the API documentation for `Deref`. Rust calls `deref` again to turn the `&String` into `&str`, which matches the `hello` function’s definition. If Rust didn’t implement deref coercion, we would have to write the code in Listing 15-13 instead of the code in Listing 15-12 to call `hello` with a value of type `&MyBox<String>`. Filename: src/main.rs ``` use std::ops::Deref; impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } fn hello(name: &str) { println!("Hello, {name}!"); } fn main() { let m = MyBox::new(String::from("Rust")); hello(&(*m)[..]); } ``` Listing 15-13: The code we would have to write if Rust didn’t have deref coercion The `(*m)` dereferences the `MyBox<String>` into a `String`. Then the `&` and `[..]` take a string slice of the `String` that is equal to the whole string to match the signature of `hello`. This code without deref coercions is harder to read, write, and understand with all of these symbols involved. Deref coercion allows Rust to handle these conversions for us automatically. When the `Deref` trait is defined for the types involved, Rust will analyze the types and use `Deref::deref` as many times as necessary to get a reference to match the parameter’s type. The number of times that `Deref::deref` needs to be inserted is resolved at compile time, so there is no runtime penalty for taking advantage of deref coercion! ### How Deref Coercion Interacts with Mutability Similar to how you use the `Deref` trait to override the `*` operator on immutable references, you can use the `DerefMut` trait to override the `*` operator on mutable references. Rust does deref coercion when it finds types and trait implementations in three cases: * From `&T` to `&U` when `T: Deref<Target=U>` * From `&mut T` to `&mut U` when `T: DerefMut<Target=U>` * From `&mut T` to `&U` when `T: Deref<Target=U>` The first two cases are the same as each other except that the second implements mutability. The first case states that if you have a `&T`, and `T` implements `Deref` to some type `U`, you can get a `&U` transparently. The second case states that the same deref coercion happens for mutable references. The third case is trickier: Rust will also coerce a mutable reference to an immutable one. But the reverse is *not* possible: immutable references will never coerce to mutable references. Because of the borrowing rules, if you have a mutable reference, that mutable reference must be the only reference to that data (otherwise, the program wouldn’t compile). Converting one mutable reference to one immutable reference will never break the borrowing rules. Converting an immutable reference to a mutable reference would require that the initial immutable reference is the only immutable reference to that data, but the borrowing rules don’t guarantee that. Therefore, Rust can’t make the assumption that converting an immutable reference to a mutable reference is possible. rust Traits: Defining Shared Behavior Traits: Defining Shared Behavior ================================ A *trait* defines functionality a particular type has and can share with other types. We can use traits to define shared behavior in an abstract way. We can use *trait bounds* to specify that a generic type can be any type that has certain behavior. > Note: Traits are similar to a feature often called *interfaces* in other languages, although with some differences. > > ### Defining a Trait A type’s behavior consists of the methods we can call on that type. Different types share the same behavior if we can call the same methods on all of those types. Trait definitions are a way to group method signatures together to define a set of behaviors necessary to accomplish some purpose. For example, let’s say we have multiple structs that hold various kinds and amounts of text: a `NewsArticle` struct that holds a news story filed in a particular location and a `Tweet` that can have at most 280 characters along with metadata that indicates whether it was a new tweet, a retweet, or a reply to another tweet. We want to make a media aggregator library crate named `aggregator` that can display summaries of data that might be stored in a `NewsArticle` or `Tweet` instance. To do this, we need a summary from each type, and we’ll request that summary by calling a `summarize` method on an instance. Listing 10-12 shows the definition of a public `Summary` trait that expresses this behavior. Filename: src/lib.rs ``` pub trait Summary { fn summarize(&self) -> String; } ``` Listing 10-12: A `Summary` trait that consists of the behavior provided by a `summarize` method Here, we declare a trait using the `trait` keyword and then the trait’s name, which is `Summary` in this case. We’ve also declared the trait as `pub` so that crates depending on this crate can make use of this trait too, as we’ll see in a few examples. Inside the curly brackets, we declare the method signatures that describe the behaviors of the types that implement this trait, which in this case is `fn summarize(&self) -> String`. After the method signature, instead of providing an implementation within curly brackets, we use a semicolon. Each type implementing this trait must provide its own custom behavior for the body of the method. The compiler will enforce that any type that has the `Summary` trait will have the method `summarize` defined with this signature exactly. A trait can have multiple methods in its body: the method signatures are listed one per line and each line ends in a semicolon. ### Implementing a Trait on a Type Now that we’ve defined the desired signatures of the `Summary` trait’s methods, we can implement it on the types in our media aggregator. Listing 10-13 shows an implementation of the `Summary` trait on the `NewsArticle` struct that uses the headline, the author, and the location to create the return value of `summarize`. For the `Tweet` struct, we define `summarize` as the username followed by the entire text of the tweet, assuming that tweet content is already limited to 280 characters. Filename: src/lib.rs ``` pub trait Summary { fn summarize(&self) -> String; } pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } impl Summary for NewsArticle { fn summarize(&self) -> String { format!("{}, by {} ({})", self.headline, self.author, self.location) } } pub struct Tweet { pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } impl Summary for Tweet { fn summarize(&self) -> String { format!("{}: {}", self.username, self.content) } } ``` Listing 10-13: Implementing the `Summary` trait on the `NewsArticle` and `Tweet` types Implementing a trait on a type is similar to implementing regular methods. The difference is that after `impl`, we put the trait name we want to implement, then use the `for` keyword, and then specify the name of the type we want to implement the trait for. Within the `impl` block, we put the method signatures that the trait definition has defined. Instead of adding a semicolon after each signature, we use curly brackets and fill in the method body with the specific behavior that we want the methods of the trait to have for the particular type. Now that the library has implemented the `Summary` trait on `NewsArticle` and `Tweet`, users of the crate can call the trait methods on instances of `NewsArticle` and `Tweet` in the same way we call regular methods. The only difference is that the user must bring the trait into scope as well as the types. Here’s an example of how a binary crate could use our `aggregator` library crate: ``` use aggregator::{Summary, Tweet}; fn main() { let tweet = Tweet { username: String::from("horse_ebooks"), content: String::from( "of course, as you probably already know, people", ), reply: false, retweet: false, }; println!("1 new tweet: {}", tweet.summarize()); } ``` This code prints `1 new tweet: horse_ebooks: of course, as you probably already know, people`. Other crates that depend on the `aggregator` crate can also bring the `Summary` trait into scope to implement `Summary` on their own types. One restriction to note is that we can implement a trait on a type only if at least one of the trait or the type is local to our crate. For example, we can implement standard library traits like `Display` on a custom type like `Tweet` as part of our `aggregator` crate functionality, because the type `Tweet` is local to our `aggregator` crate. We can also implement `Summary` on `Vec<T>` in our `aggregator` crate, because the trait `Summary` is local to our `aggregator` crate. But we can’t implement external traits on external types. For example, we can’t implement the `Display` trait on `Vec<T>` within our `aggregator` crate, because `Display` and `Vec<T>` are both defined in the standard library and aren’t local to our `aggregator` crate. This restriction is part of a property called *coherence*, and more specifically the *orphan rule*, so named because the parent type is not present. This rule ensures that other people’s code can’t break your code and vice versa. Without the rule, two crates could implement the same trait for the same type, and Rust wouldn’t know which implementation to use. ### Default Implementations Sometimes it’s useful to have default behavior for some or all of the methods in a trait instead of requiring implementations for all methods on every type. Then, as we implement the trait on a particular type, we can keep or override each method’s default behavior. In Listing 10-14 we specify a default string for the `summarize` method of the `Summary` trait instead of only defining the method signature, as we did in Listing 10-12. Filename: src/lib.rs ``` pub trait Summary { fn summarize(&self) -> String { String::from("(Read more...)") } } pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } impl Summary for NewsArticle {} pub struct Tweet { pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } impl Summary for Tweet { fn summarize(&self) -> String { format!("{}: {}", self.username, self.content) } } ``` Listing 10-14: Defining a `Summary` trait with a default implementation of the `summarize` method To use a default implementation to summarize instances of `NewsArticle`, we specify an empty `impl` block with `impl Summary for NewsArticle {}`. Even though we’re no longer defining the `summarize` method on `NewsArticle` directly, we’ve provided a default implementation and specified that `NewsArticle` implements the `Summary` trait. As a result, we can still call the `summarize` method on an instance of `NewsArticle`, like this: ``` use aggregator::{self, NewsArticle, Summary}; fn main() { let article = NewsArticle { headline: String::from("Penguins win the Stanley Cup Championship!"), location: String::from("Pittsburgh, PA, USA"), author: String::from("Iceburgh"), content: String::from( "The Pittsburgh Penguins once again are the best \ hockey team in the NHL.", ), }; println!("New article available! {}", article.summarize()); } ``` This code prints `New article available! (Read more...)`. Creating a default implementation doesn’t require us to change anything about the implementation of `Summary` on `Tweet` in Listing 10-13. The reason is that the syntax for overriding a default implementation is the same as the syntax for implementing a trait method that doesn’t have a default implementation. Default implementations can call other methods in the same trait, even if those other methods don’t have a default implementation. In this way, a trait can provide a lot of useful functionality and only require implementors to specify a small part of it. For example, we could define the `Summary` trait to have a `summarize_author` method whose implementation is required, and then define a `summarize` method that has a default implementation that calls the `summarize_author` method: ``` pub trait Summary { fn summarize_author(&self) -> String; fn summarize(&self) -> String { format!("(Read more from {}...)", self.summarize_author()) } } pub struct Tweet { pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } impl Summary for Tweet { fn summarize_author(&self) -> String { format!("@{}", self.username) } } ``` To use this version of `Summary`, we only need to define `summarize_author` when we implement the trait on a type: ``` pub trait Summary { fn summarize_author(&self) -> String; fn summarize(&self) -> String { format!("(Read more from {}...)", self.summarize_author()) } } pub struct Tweet { pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } impl Summary for Tweet { fn summarize_author(&self) -> String { format!("@{}", self.username) } } ``` After we define `summarize_author`, we can call `summarize` on instances of the `Tweet` struct, and the default implementation of `summarize` will call the definition of `summarize_author` that we’ve provided. Because we’ve implemented `summarize_author`, the `Summary` trait has given us the behavior of the `summarize` method without requiring us to write any more code. ``` use aggregator::{self, Summary, Tweet}; fn main() { let tweet = Tweet { username: String::from("horse_ebooks"), content: String::from( "of course, as you probably already know, people", ), reply: false, retweet: false, }; println!("1 new tweet: {}", tweet.summarize()); } ``` This code prints `1 new tweet: (Read more from @horse_ebooks...)`. Note that it isn’t possible to call the default implementation from an overriding implementation of that same method. ### Traits as Parameters Now that you know how to define and implement traits, we can explore how to use traits to define functions that accept many different types. We'll use the `Summary` trait we implemented on the `NewsArticle` and `Tweet` types in Listing 10-13 to define a `notify` function that calls the `summarize` method on its `item` parameter, which is of some type that implements the `Summary` trait. To do this, we use the `impl Trait` syntax, like this: ``` pub trait Summary { fn summarize(&self) -> String; } pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } impl Summary for NewsArticle { fn summarize(&self) -> String { format!("{}, by {} ({})", self.headline, self.author, self.location) } } pub struct Tweet { pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } impl Summary for Tweet { fn summarize(&self) -> String { format!("{}: {}", self.username, self.content) } } pub fn notify(item: &impl Summary) { println!("Breaking news! {}", item.summarize()); } ``` Instead of a concrete type for the `item` parameter, we specify the `impl` keyword and the trait name. This parameter accepts any type that implements the specified trait. In the body of `notify`, we can call any methods on `item` that come from the `Summary` trait, such as `summarize`. We can call `notify` and pass in any instance of `NewsArticle` or `Tweet`. Code that calls the function with any other type, such as a `String` or an `i32`, won’t compile because those types don’t implement `Summary`. #### Trait Bound Syntax The `impl Trait` syntax works for straightforward cases but is actually syntax sugar for a longer form known as a *trait bound*; it looks like this: ``` pub fn notify<T: Summary>(item: &T) { println!("Breaking news! {}", item.summarize()); } ``` This longer form is equivalent to the example in the previous section but is more verbose. We place trait bounds with the declaration of the generic type parameter after a colon and inside angle brackets. The `impl Trait` syntax is convenient and makes for more concise code in simple cases, while the fuller trait bound syntax can express more complexity in other cases. For example, we can have two parameters that implement `Summary`. Doing so with the `impl Trait` syntax looks like this: ``` pub fn notify(item1: &impl Summary, item2: &impl Summary) { ``` Using `impl Trait` is appropriate if we want this function to allow `item1` and `item2` to have different types (as long as both types implement `Summary`). If we want to force both parameters to have the same type, however, we must use a trait bound, like this: ``` pub fn notify<T: Summary>(item1: &T, item2: &T) { ``` The generic type `T` specified as the type of the `item1` and `item2` parameters constrains the function such that the concrete type of the value passed as an argument for `item1` and `item2` must be the same. #### Specifying Multiple Trait Bounds with the `+` Syntax We can also specify more than one trait bound. Say we wanted `notify` to use display formatting as well as `summarize` on `item`: we specify in the `notify` definition that `item` must implement both `Display` and `Summary`. We can do so using the `+` syntax: ``` pub fn notify(item: &(impl Summary + Display)) { ``` The `+` syntax is also valid with trait bounds on generic types: ``` pub fn notify<T: Summary + Display>(item: &T) { ``` With the two trait bounds specified, the body of `notify` can call `summarize` and use `{}` to format `item`. #### Clearer Trait Bounds with `where` Clauses Using too many trait bounds has its downsides. Each generic has its own trait bounds, so functions with multiple generic type parameters can contain lots of trait bound information between the function’s name and its parameter list, making the function signature hard to read. For this reason, Rust has alternate syntax for specifying trait bounds inside a `where` clause after the function signature. So instead of writing this: ``` fn some_function<T: Display + Clone, U: Clone + Debug>(t: &T, u: &U) -> i32 { ``` we can use a `where` clause, like this: ``` fn some_function<T, U>(t: &T, u: &U) -> i32 where T: Display + Clone, U: Clone + Debug, { unimplemented!() } ``` This function’s signature is less cluttered: the function name, parameter list, and return type are close together, similar to a function without lots of trait bounds. ### Returning Types that Implement Traits We can also use the `impl Trait` syntax in the return position to return a value of some type that implements a trait, as shown here: ``` pub trait Summary { fn summarize(&self) -> String; } pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } impl Summary for NewsArticle { fn summarize(&self) -> String { format!("{}, by {} ({})", self.headline, self.author, self.location) } } pub struct Tweet { pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } impl Summary for Tweet { fn summarize(&self) -> String { format!("{}: {}", self.username, self.content) } } fn returns_summarizable() -> impl Summary { Tweet { username: String::from("horse_ebooks"), content: String::from( "of course, as you probably already know, people", ), reply: false, retweet: false, } } ``` By using `impl Summary` for the return type, we specify that the `returns_summarizable` function returns some type that implements the `Summary` trait without naming the concrete type. In this case, `returns_summarizable` returns a `Tweet`, but the code calling this function doesn’t need to know that. The ability to specify a return type only by the trait it implements is especially useful in the context of closures and iterators, which we cover in Chapter 13. Closures and iterators create types that only the compiler knows or types that are very long to specify. The `impl Trait` syntax lets you concisely specify that a function returns some type that implements the `Iterator` trait without needing to write out a very long type. However, you can only use `impl Trait` if you’re returning a single type. For example, this code that returns either a `NewsArticle` or a `Tweet` with the return type specified as `impl Summary` wouldn’t work: ``` pub trait Summary { fn summarize(&self) -> String; } pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } impl Summary for NewsArticle { fn summarize(&self) -> String { format!("{}, by {} ({})", self.headline, self.author, self.location) } } pub struct Tweet { pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } impl Summary for Tweet { fn summarize(&self) -> String { format!("{}: {}", self.username, self.content) } } fn returns_summarizable(switch: bool) -> impl Summary { if switch { NewsArticle { headline: String::from( "Penguins win the Stanley Cup Championship!", ), location: String::from("Pittsburgh, PA, USA"), author: String::from("Iceburgh"), content: String::from( "The Pittsburgh Penguins once again are the best \ hockey team in the NHL.", ), } } else { Tweet { username: String::from("horse_ebooks"), content: String::from( "of course, as you probably already know, people", ), reply: false, retweet: false, } } } ``` Returning either a `NewsArticle` or a `Tweet` isn’t allowed due to restrictions around how the `impl Trait` syntax is implemented in the compiler. We’ll cover how to write a function with this behavior in the [“Using Trait Objects That Allow for Values of Different Types”](ch17-02-trait-objects#using-trait-objects-that-allow-for-values-of-different-types) section of Chapter 17. ### Using Trait Bounds to Conditionally Implement Methods By using a trait bound with an `impl` block that uses generic type parameters, we can implement methods conditionally for types that implement the specified traits. For example, the type `Pair<T>` in Listing 10-15 always implements the `new` function to return a new instance of `Pair<T>` (recall from the [“Defining Methods”](ch05-03-method-syntax#defining-methods) section of Chapter 5 that `Self` is a type alias for the type of the `impl` block, which in this case is `Pair<T>`). But in the next `impl` block, `Pair<T>` only implements the `cmp_display` method if its inner type `T` implements the `PartialOrd` trait that enables comparison *and* the `Display` trait that enables printing. Filename: src/lib.rs ``` use std::fmt::Display; struct Pair<T> { x: T, y: T, } impl<T> Pair<T> { fn new(x: T, y: T) -> Self { Self { x, y } } } impl<T: Display + PartialOrd> Pair<T> { fn cmp_display(&self) { if self.x >= self.y { println!("The largest member is x = {}", self.x); } else { println!("The largest member is y = {}", self.y); } } } ``` Listing 10-15: Conditionally implementing methods on a generic type depending on trait bounds We can also conditionally implement a trait for any type that implements another trait. Implementations of a trait on any type that satisfies the trait bounds are called *blanket implementations* and are extensively used in the Rust standard library. For example, the standard library implements the `ToString` trait on any type that implements the `Display` trait. The `impl` block in the standard library looks similar to this code: ``` impl<T: Display> ToString for T { // --snip-- } ``` Because the standard library has this blanket implementation, we can call the `to_string` method defined by the `ToString` trait on any type that implements the `Display` trait. For example, we can turn integers into their corresponding `String` values like this because integers implement `Display`: ``` #![allow(unused)] fn main() { let s = 3.to_string(); } ``` Blanket implementations appear in the documentation for the trait in the “Implementors” section. Traits and trait bounds let us write code that uses generic type parameters to reduce duplication but also specify to the compiler that we want the generic type to have particular behavior. The compiler can then use the trait bound information to check that all the concrete types used with our code provide the correct behavior. In dynamically typed languages, we would get an error at runtime if we called a method on a type which didn’t define the method. But Rust moves these errors to compile time so we’re forced to fix the problems before our code is even able to run. Additionally, we don’t have to write code that checks for behavior at runtime because we’ve already checked at compile time. Doing so improves performance without having to give up the flexibility of generics.
programming_docs
rust Advanced Functions and Closures Advanced Functions and Closures =============================== This section explores some advanced features related to functions and closures, including function pointers and returning closures. ### Function Pointers We’ve talked about how to pass closures to functions; you can also pass regular functions to functions! This technique is useful when you want to pass a function you’ve already defined rather than defining a new closure. Functions coerce to the type `fn` (with a lowercase f), not to be confused with the `Fn` closure trait. The `fn` type is called a *function pointer*. Passing functions with function pointers will allow you to use functions as arguments to other functions. The syntax for specifying that a parameter is a function pointer is similar to that of closures, as shown in Listing 19-27, where we’ve defined a function `add_one` that adds one to its parameter. The function `do_twice` takes two parameters: a function pointer to any function that takes an `i32` parameter and returns an `i32`, and one `i32 value`. The `do_twice` function calls the function `f` twice, passing it the `arg` value, then adds the two function call results together. The `main` function calls `do_twice` with the arguments `add_one` and `5`. Filename: src/main.rs ``` fn add_one(x: i32) -> i32 { x + 1 } fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { f(arg) + f(arg) } fn main() { let answer = do_twice(add_one, 5); println!("The answer is: {}", answer); } ``` Listing 19-27: Using the `fn` type to accept a function pointer as an argument This code prints `The answer is: 12`. We specify that the parameter `f` in `do_twice` is an `fn` that takes one parameter of type `i32` and returns an `i32`. We can then call `f` in the body of `do_twice`. In `main`, we can pass the function name `add_one` as the first argument to `do_twice`. Unlike closures, `fn` is a type rather than a trait, so we specify `fn` as the parameter type directly rather than declaring a generic type parameter with one of the `Fn` traits as a trait bound. Function pointers implement all three of the closure traits (`Fn`, `FnMut`, and `FnOnce`), meaning you can always pass a function pointer as an argument for a function that expects a closure. It’s best to write functions using a generic type and one of the closure traits so your functions can accept either functions or closures. That said, one example of where you would want to only accept `fn` and not closures is when interfacing with external code that doesn’t have closures: C functions can accept functions as arguments, but C doesn’t have closures. As an example of where you could use either a closure defined inline or a named function, let’s look at a use of the `map` method provided by the `Iterator` trait in the standard library. To use the `map` function to turn a vector of numbers into a vector of strings, we could use a closure, like this: ``` fn main() { let list_of_numbers = vec![1, 2, 3]; let list_of_strings: Vec<String> = list_of_numbers.iter().map(|i| i.to_string()).collect(); } ``` Or we could name a function as the argument to `map` instead of the closure, like this: ``` fn main() { let list_of_numbers = vec![1, 2, 3]; let list_of_strings: Vec<String> = list_of_numbers.iter().map(ToString::to_string).collect(); } ``` Note that we must use the fully qualified syntax that we talked about earlier in the [“Advanced Traits”](ch19-03-advanced-traits#advanced-traits) section because there are multiple functions available named `to_string`. Here, we’re using the `to_string` function defined in the `ToString` trait, which the standard library has implemented for any type that implements `Display`. Recall from the [“Enum values”](ch06-01-defining-an-enum#enum-values) section of Chapter 6 that the name of each enum variant that we define also becomes an initializer function. We can use these initializer functions as function pointers that implement the closure traits, which means we can specify the initializer functions as arguments for methods that take closures, like so: ``` fn main() { enum Status { Value(u32), Stop, } let list_of_statuses: Vec<Status> = (0u32..20).map(Status::Value).collect(); } ``` Here we create `Status::Value` instances using each `u32` value in the range that `map` is called on by using the initializer function of `Status::Value`. Some people prefer this style, and some people prefer to use closures. They compile to the same code, so use whichever style is clearer to you. ### Returning Closures Closures are represented by traits, which means you can’t return closures directly. In most cases where you might want to return a trait, you can instead use the concrete type that implements the trait as the return value of the function. However, you can’t do that with closures because they don’t have a concrete type that is returnable; you’re not allowed to use the function pointer `fn` as a return type, for example. The following code tries to return a closure directly, but it won’t compile: ``` fn returns_closure() -> dyn Fn(i32) -> i32 { |x| x + 1 } ``` The compiler error is as follows: ``` $ cargo build Compiling functions-example v0.1.0 (file:///projects/functions-example) error[E0746]: return type cannot have an unboxed trait object --> src/lib.rs:1:25 | 1 | fn returns_closure() -> dyn Fn(i32) -> i32 { | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | = note: for information on `impl Trait`, see <https://doc.rust-lang.org/book/ch10-02-traits.html#returning-types-that-implement-traits> help: use `impl Fn(i32) -> i32` as the return type, as all return paths are of type `[closure@src/lib.rs:2:5: 2:14]`, which implements `Fn(i32) -> i32` | 1 | fn returns_closure() -> impl Fn(i32) -> i32 { | ~~~~~~~~~~~~~~~~~~~ For more information about this error, try `rustc --explain E0746`. error: could not compile `functions-example` due to previous error ``` The error references the `Sized` trait again! Rust doesn’t know how much space it will need to store the closure. We saw a solution to this problem earlier. We can use a trait object: ``` fn returns_closure() -> Box<dyn Fn(i32) -> i32> { Box::new(|x| x + 1) } ``` This code will compile just fine. For more about trait objects, refer to the section [“Using Trait Objects That Allow for Values of Different Types”](ch17-02-trait-objects#using-trait-objects-that-allow-for-values-of-different-types) in Chapter 17. Next, let’s look at macros! rust What Is Ownership? What Is Ownership? ================== *Ownership* is a set of rules that governs how a Rust program manages memory. All programs have to manage the way they use a computer’s memory while running. Some languages have garbage collection that regularly looks for no-longer used memory as the program runs; in other languages, the programmer must explicitly allocate and free the memory. Rust uses a third approach: memory is managed through a system of ownership with a set of rules that the compiler checks. If any of the rules are violated, the program won’t compile. None of the features of ownership will slow down your program while it’s running. Because ownership is a new concept for many programmers, it does take some time to get used to. The good news is that the more experienced you become with Rust and the rules of the ownership system, the easier you’ll find it to naturally develop code that is safe and efficient. Keep at it! When you understand ownership, you’ll have a solid foundation for understanding the features that make Rust unique. In this chapter, you’ll learn ownership by working through some examples that focus on a very common data structure: strings. > ### The Stack and the Heap > > Many programming languages don’t require you to think about the stack and the heap very often. But in a systems programming language like Rust, whether a value is on the stack or the heap affects how the language behaves and why you have to make certain decisions. Parts of ownership will be described in relation to the stack and the heap later in this chapter, so here is a brief explanation in preparation. > > Both the stack and the heap are parts of memory available to your code to use at runtime, but they are structured in different ways. The stack stores values in the order it gets them and removes the values in the opposite order. This is referred to as *last in, first out*. Think of a stack of plates: when you add more plates, you put them on top of the pile, and when you need a plate, you take one off the top. Adding or removing plates from the middle or bottom wouldn’t work as well! Adding data is called *pushing onto the stack*, and removing data is called *popping off the stack*. All data stored on the stack must have a known, fixed size. Data with an unknown size at compile time or a size that might change must be stored on the heap instead. > > The heap is less organized: when you put data on the heap, you request a certain amount of space. The memory allocator finds an empty spot in the heap that is big enough, marks it as being in use, and returns a *pointer*, which is the address of that location. This process is called *allocating on the heap* and is sometimes abbreviated as just *allocating* (pushing values onto the stack is not considered allocating). Because the pointer to the heap is a known, fixed size, you can store the pointer on the stack, but when you want the actual data, you must follow the pointer. Think of being seated at a restaurant. When you enter, you state the number of people in your group, and the staff finds an empty table that fits everyone and leads you there. If someone in your group comes late, they can ask where you’ve been seated to find you. > > Pushing to the stack is faster than allocating on the heap because the allocator never has to search for a place to store new data; that location is always at the top of the stack. Comparatively, allocating space on the heap requires more work, because the allocator must first find a big enough space to hold the data and then perform bookkeeping to prepare for the next allocation. > > Accessing data in the heap is slower than accessing data on the stack because you have to follow a pointer to get there. Contemporary processors are faster if they jump around less in memory. Continuing the analogy, consider a server at a restaurant taking orders from many tables. It’s most efficient to get all the orders at one table before moving on to the next table. Taking an order from table A, then an order from table B, then one from A again, and then one from B again would be a much slower process. By the same token, a processor can do its job better if it works on data that’s close to other data (as it is on the stack) rather than farther away (as it can be on the heap). > > When your code calls a function, the values passed into the function (including, potentially, pointers to data on the heap) and the function’s local variables get pushed onto the stack. When the function is over, those values get popped off the stack. > > Keeping track of what parts of code are using what data on the heap, minimizing the amount of duplicate data on the heap, and cleaning up unused data on the heap so you don’t run out of space are all problems that ownership addresses. Once you understand ownership, you won’t need to think about the stack and the heap very often, but knowing that the main purpose of ownership is to manage heap data can help explain why it works the way it does. > > ### Ownership Rules First, let’s take a look at the ownership rules. Keep these rules in mind as we work through the examples that illustrate them: * Each value in Rust has an *owner*. * There can only be one owner at a time. * When the owner goes out of scope, the value will be dropped. ### Variable Scope Now that we’re past basic Rust syntax, we won’t include all the `fn main() {` code in examples, so if you’re following along, make sure to put the following examples inside a `main` function manually. As a result, our examples will be a bit more concise, letting us focus on the actual details rather than boilerplate code. As a first example of ownership, we’ll look at the *scope* of some variables. A scope is the range within a program for which an item is valid. Take the following variable: ``` #![allow(unused)] fn main() { let s = "hello"; } ``` The variable `s` refers to a string literal, where the value of the string is hardcoded into the text of our program. The variable is valid from the point at which it’s declared until the end of the current *scope*. Listing 4-1 shows a program with comments annotating where the variable `s` would be valid. ``` fn main() { { // s is not valid here, it’s not yet declared let s = "hello"; // s is valid from this point forward // do stuff with s } // this scope is now over, and s is no longer valid } ``` Listing 4-1: A variable and the scope in which it is valid In other words, there are two important points in time here: * When `s` comes *into scope*, it is valid. * It remains valid until it goes *out of scope*. At this point, the relationship between scopes and when variables are valid is similar to that in other programming languages. Now we’ll build on top of this understanding by introducing the `String` type. ### The `String` Type To illustrate the rules of ownership, we need a data type that is more complex than those we covered in the [“Data Types”](ch03-02-data-types#data-types) section of Chapter 3. The types covered previously are all a known size, can be stored on the stack and popped off the stack when their scope is over, and can be quickly and trivially copied to make a new, independent instance if another part of code needs to use the same value in a different scope. But we want to look at data that is stored on the heap and explore how Rust knows when to clean up that data, and the `String` type is a great example. We’ll concentrate on the parts of `String` that relate to ownership. These aspects also apply to other complex data types, whether they are provided by the standard library or created by you. We’ll discuss `String` in more depth in [Chapter 8](ch08-02-strings). We’ve already seen string literals, where a string value is hardcoded into our program. String literals are convenient, but they aren’t suitable for every situation in which we may want to use text. One reason is that they’re immutable. Another is that not every string value can be known when we write our code: for example, what if we want to take user input and store it? For these situations, Rust has a second string type, `String`. This type manages data allocated on the heap and as such is able to store an amount of text that is unknown to us at compile time. You can create a `String` from a string literal using the `from` function, like so: ``` #![allow(unused)] fn main() { let s = String::from("hello"); } ``` The double colon `::` operator allows us to namespace this particular `from` function under the `String` type rather than using some sort of name like `string_from`. We’ll discuss this syntax more in the [“Method Syntax”](ch05-03-method-syntax#method-syntax) section of Chapter 5 and when we talk about namespacing with modules in [“Paths for Referring to an Item in the Module Tree”](ch07-03-paths-for-referring-to-an-item-in-the-module-tree) in Chapter 7. This kind of string *can* be mutated: ``` fn main() { let mut s = String::from("hello"); s.push_str(", world!"); // push_str() appends a literal to a String println!("{}", s); // This will print `hello, world!` } ``` So, what’s the difference here? Why can `String` be mutated but literals cannot? The difference is how these two types deal with memory. ### Memory and Allocation In the case of a string literal, we know the contents at compile time, so the text is hardcoded directly into the final executable. This is why string literals are fast and efficient. But these properties only come from the string literal’s immutability. Unfortunately, we can’t put a blob of memory into the binary for each piece of text whose size is unknown at compile time and whose size might change while running the program. With the `String` type, in order to support a mutable, growable piece of text, we need to allocate an amount of memory on the heap, unknown at compile time, to hold the contents. This means: * The memory must be requested from the memory allocator at runtime. * We need a way of returning this memory to the allocator when we’re done with our `String`. That first part is done by us: when we call `String::from`, its implementation requests the memory it needs. This is pretty much universal in programming languages. However, the second part is different. In languages with a *garbage collector (GC)*, the GC keeps track of and cleans up memory that isn’t being used anymore, and we don’t need to think about it. In most languages without a GC, it’s our responsibility to identify when memory is no longer being used and call code to explicitly free it, just as we did to request it. Doing this correctly has historically been a difficult programming problem. If we forget, we’ll waste memory. If we do it too early, we’ll have an invalid variable. If we do it twice, that’s a bug too. We need to pair exactly one `allocate` with exactly one `free`. Rust takes a different path: the memory is automatically returned once the variable that owns it goes out of scope. Here’s a version of our scope example from Listing 4-1 using a `String` instead of a string literal: ``` fn main() { { let s = String::from("hello"); // s is valid from this point forward // do stuff with s } // this scope is now over, and s is no // longer valid } ``` There is a natural point at which we can return the memory our `String` needs to the allocator: when `s` goes out of scope. When a variable goes out of scope, Rust calls a special function for us. This function is called [`drop`](../std/ops/trait.drop#tymethod.drop), and it’s where the author of `String` can put the code to return the memory. Rust calls `drop` automatically at the closing curly bracket. > Note: In C++, this pattern of deallocating resources at the end of an item’s lifetime is sometimes called *Resource Acquisition Is Initialization (RAII)*. The `drop` function in Rust will be familiar to you if you’ve used RAII patterns. > > This pattern has a profound impact on the way Rust code is written. It may seem simple right now, but the behavior of code can be unexpected in more complicated situations when we want to have multiple variables use the data we’ve allocated on the heap. Let’s explore some of those situations now. #### Ways Variables and Data Interact: Move Multiple variables can interact with the same data in different ways in Rust. Let’s look at an example using an integer in Listing 4-2. ``` fn main() { let x = 5; let y = x; } ``` Listing 4-2: Assigning the integer value of variable `x` to `y` We can probably guess what this is doing: “bind the value `5` to `x`; then make a copy of the value in `x` and bind it to `y`.” We now have two variables, `x` and `y`, and both equal `5`. This is indeed what is happening, because integers are simple values with a known, fixed size, and these two `5` values are pushed onto the stack. Now let’s look at the `String` version: ``` fn main() { let s1 = String::from("hello"); let s2 = s1; } ``` This looks very similar, so we might assume that the way it works would be the same: that is, the second line would make a copy of the value in `s1` and bind it to `s2`. But this isn’t quite what happens. Take a look at Figure 4-1 to see what is happening to `String` under the covers. A `String` is made up of three parts, shown on the left: a pointer to the memory that holds the contents of the string, a length, and a capacity. This group of data is stored on the stack. On the right is the memory on the heap that holds the contents. Figure 4-1: Representation in memory of a `String` holding the value `"hello"` bound to `s1` The length is how much memory, in bytes, the contents of the `String` is currently using. The capacity is the total amount of memory, in bytes, that the `String` has received from the allocator. The difference between length and capacity matters, but not in this context, so for now, it’s fine to ignore the capacity. When we assign `s1` to `s2`, the `String` data is copied, meaning we copy the pointer, the length, and the capacity that are on the stack. We do not copy the data on the heap that the pointer refers to. In other words, the data representation in memory looks like Figure 4-2. Figure 4-2: Representation in memory of the variable `s2` that has a copy of the pointer, length, and capacity of `s1` The representation does *not* look like Figure 4-3, which is what memory would look like if Rust instead copied the heap data as well. If Rust did this, the operation `s2 = s1` could be very expensive in terms of runtime performance if the data on the heap were large. Figure 4-3: Another possibility for what `s2 = s1` might do if Rust copied the heap data as well Earlier, we said that when a variable goes out of scope, Rust automatically calls the `drop` function and cleans up the heap memory for that variable. But Figure 4-2 shows both data pointers pointing to the same location. This is a problem: when `s2` and `s1` go out of scope, they will both try to free the same memory. This is known as a *double free* error and is one of the memory safety bugs we mentioned previously. Freeing memory twice can lead to memory corruption, which can potentially lead to security vulnerabilities. To ensure memory safety, after the line `let s2 = s1`, Rust considers `s1` as no longer valid. Therefore, Rust doesn’t need to free anything when `s1` goes out of scope. Check out what happens when you try to use `s1` after `s2` is created; it won’t work: ``` fn main() { let s1 = String::from("hello"); let s2 = s1; println!("{}, world!", s1); } ``` You’ll get an error like this because Rust prevents you from using the invalidated reference: ``` $ cargo run Compiling ownership v0.1.0 (file:///projects/ownership) error[E0382]: borrow of moved value: `s1` --> src/main.rs:5:28 | 2 | let s1 = String::from("hello"); | -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait 3 | let s2 = s1; | -- value moved here 4 | 5 | println!("{}, world!", s1); | ^^ value borrowed here after move | = note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info) For more information about this error, try `rustc --explain E0382`. error: could not compile `ownership` due to previous error ``` If you’ve heard the terms *shallow copy* and *deep copy* while working with other languages, the concept of copying the pointer, length, and capacity without copying the data probably sounds like making a shallow copy. But because Rust also invalidates the first variable, instead of calling it a shallow copy, it’s known as a *move*. In this example, we would say that `s1` was *moved* into `s2`. So what actually happens is shown in Figure 4-4. Figure 4-4: Representation in memory after `s1` has been invalidated That solves our problem! With only `s2` valid, when it goes out of scope, it alone will free the memory, and we’re done. In addition, there’s a design choice that’s implied by this: Rust will never automatically create “deep” copies of your data. Therefore, any *automatic* copying can be assumed to be inexpensive in terms of runtime performance. #### Ways Variables and Data Interact: Clone If we *do* want to deeply copy the heap data of the `String`, not just the stack data, we can use a common method called `clone`. We’ll discuss method syntax in Chapter 5, but because methods are a common feature in many programming languages, you’ve probably seen them before. Here’s an example of the `clone` method in action: ``` fn main() { let s1 = String::from("hello"); let s2 = s1.clone(); println!("s1 = {}, s2 = {}", s1, s2); } ``` This works just fine and explicitly produces the behavior shown in Figure 4-3, where the heap data *does* get copied. When you see a call to `clone`, you know that some arbitrary code is being executed and that code may be expensive. It’s a visual indicator that something different is going on. #### Stack-Only Data: Copy There’s another wrinkle we haven’t talked about yet. This code using integers – part of which was shown in Listing 4-2 – works and is valid: ``` fn main() { let x = 5; let y = x; println!("x = {}, y = {}", x, y); } ``` But this code seems to contradict what we just learned: we don’t have a call to `clone`, but `x` is still valid and wasn’t moved into `y`. The reason is that types such as integers that have a known size at compile time are stored entirely on the stack, so copies of the actual values are quick to make. That means there’s no reason we would want to prevent `x` from being valid after we create the variable `y`. In other words, there’s no difference between deep and shallow copying here, so calling `clone` wouldn’t do anything different from the usual shallow copying and we can leave it out. Rust has a special annotation called the `Copy` trait that we can place on types that are stored on the stack, as integers are (we’ll talk more about traits in [Chapter 10](ch10-02-traits)). If a type implements the `Copy` trait, variables that use it do not move, but rather are trivially copied, making them still valid after assignment to another variable. Rust won’t let us annotate a type with `Copy` if the type, or any of its parts, has implemented the `Drop` trait. If the type needs something special to happen when the value goes out of scope and we add the `Copy` annotation to that type, we’ll get a compile-time error. To learn about how to add the `Copy` annotation to your type to implement the trait, see [“Derivable Traits”](appendix-03-derivable-traits) in Appendix C. So what types implement the `Copy` trait? You can check the documentation for the given type to be sure, but as a general rule, any group of simple scalar values can implement `Copy`, and nothing that requires allocation or is some form of resource can implement `Copy`. Here are some of the types that implement `Copy`: * All the integer types, such as `u32`. * The Boolean type, `bool`, with values `true` and `false`. * All the floating point types, such as `f64`. * The character type, `char`. * Tuples, if they only contain types that also implement `Copy`. For example, `(i32, i32)` implements `Copy`, but `(i32, String)` does not. ### Ownership and Functions The mechanics of passing a value to a function are similar to those when assigning a value to a variable. Passing a variable to a function will move or copy, just as assignment does. Listing 4-3 has an example with some annotations showing where variables go into and out of scope. Filename: src/main.rs ``` fn main() { let s = String::from("hello"); // s comes into scope takes_ownership(s); // s's value moves into the function... // ... and so is no longer valid here let x = 5; // x comes into scope makes_copy(x); // x would move into the function, // but i32 is Copy, so it's okay to still // use x afterward } // Here, x goes out of scope, then s. But because s's value was moved, nothing // special happens. fn takes_ownership(some_string: String) { // some_string comes into scope println!("{}", some_string); } // Here, some_string goes out of scope and `drop` is called. The backing // memory is freed. fn makes_copy(some_integer: i32) { // some_integer comes into scope println!("{}", some_integer); } // Here, some_integer goes out of scope. Nothing special happens. ``` Listing 4-3: Functions with ownership and scope annotated If we tried to use `s` after the call to `takes_ownership`, Rust would throw a compile-time error. These static checks protect us from mistakes. Try adding code to `main` that uses `s` and `x` to see where you can use them and where the ownership rules prevent you from doing so. ### Return Values and Scope Returning values can also transfer ownership. Listing 4-4 shows an example of a function that returns some value, with similar annotations as those in Listing 4-3. Filename: src/main.rs ``` fn main() { let s1 = gives_ownership(); // gives_ownership moves its return // value into s1 let s2 = String::from("hello"); // s2 comes into scope let s3 = takes_and_gives_back(s2); // s2 is moved into // takes_and_gives_back, which also // moves its return value into s3 } // Here, s3 goes out of scope and is dropped. s2 was moved, so nothing // happens. s1 goes out of scope and is dropped. fn gives_ownership() -> String { // gives_ownership will move its // return value into the function // that calls it let some_string = String::from("yours"); // some_string comes into scope some_string // some_string is returned and // moves out to the calling // function } // This function takes a String and returns one fn takes_and_gives_back(a_string: String) -> String { // a_string comes into // scope a_string // a_string is returned and moves out to the calling function } ``` Listing 4-4: Transferring ownership of return values The ownership of a variable follows the same pattern every time: assigning a value to another variable moves it. When a variable that includes data on the heap goes out of scope, the value will be cleaned up by `drop` unless ownership of the data has been moved to another variable. While this works, taking ownership and then returning ownership with every function is a bit tedious. What if we want to let a function use a value but not take ownership? It’s quite annoying that anything we pass in also needs to be passed back if we want to use it again, in addition to any data resulting from the body of the function that we might want to return as well. Rust does let us return multiple values using a tuple, as shown in Listing 4-5. Filename: src/main.rs ``` fn main() { let s1 = String::from("hello"); let (s2, len) = calculate_length(s1); println!("The length of '{}' is {}.", s2, len); } fn calculate_length(s: String) -> (String, usize) { let length = s.len(); // len() returns the length of a String (s, length) } ``` Listing 4-5: Returning ownership of parameters But this is too much ceremony and a lot of work for a concept that should be common. Luckily for us, Rust has a feature for using a value without transferring ownership, called *references*.
programming_docs
rust Defining and Instantiating Structs Defining and Instantiating Structs ================================== Structs are similar to tuples, discussed in [“The Tuple Type”](ch03-02-data-types#the-tuple-type) section, in that both hold multiple related values. Like tuples, the pieces of a struct can be different types. Unlike with tuples, in a struct you’ll name each piece of data so it’s clear what the values mean. Adding these names means that structs are more flexible than tuples: you don’t have to rely on the order of the data to specify or access the values of an instance. To define a struct, we enter the keyword `struct` and name the entire struct. A struct’s name should describe the significance of the pieces of data being grouped together. Then, inside curly brackets, we define the names and types of the pieces of data, which we call *fields*. For example, Listing 5-1 shows a struct that stores information about a user account. ``` struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() {} ``` Listing 5-1: A `User` struct definition To use a struct after we’ve defined it, we create an *instance* of that struct by specifying concrete values for each of the fields. We create an instance by stating the name of the struct and then add curly brackets containing `key: value` pairs, where the keys are the names of the fields and the values are the data we want to store in those fields. We don’t have to specify the fields in the same order in which we declared them in the struct. In other words, the struct definition is like a general template for the type, and instances fill in that template with particular data to create values of the type. For example, we can declare a particular user as shown in Listing 5-2. ``` struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() { let user1 = User { email: String::from("[email protected]"), username: String::from("someusername123"), active: true, sign_in_count: 1, }; } ``` Listing 5-2: Creating an instance of the `User` struct To get a specific value from a struct, we use dot notation. For example, to access this user’s email address, we use `user1.email`. If the instance is mutable, we can change a value by using the dot notation and assigning into a particular field. Listing 5-3 shows how to change the value in the `email` field of a mutable `User` instance. ``` struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() { let mut user1 = User { email: String::from("[email protected]"), username: String::from("someusername123"), active: true, sign_in_count: 1, }; user1.email = String::from("[email protected]"); } ``` Listing 5-3: Changing the value in the `email` field of a `User` instance Note that the entire instance must be mutable; Rust doesn’t allow us to mark only certain fields as mutable. As with any expression, we can construct a new instance of the struct as the last expression in the function body to implicitly return that new instance. Listing 5-4 shows a `build_user` function that returns a `User` instance with the given email and username. The `active` field gets the value of `true`, and the `sign_in_count` gets a value of `1`. ``` struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn build_user(email: String, username: String) -> User { User { email: email, username: username, active: true, sign_in_count: 1, } } fn main() { let user1 = build_user( String::from("[email protected]"), String::from("someusername123"), ); } ``` Listing 5-4: A `build_user` function that takes an email and username and returns a `User` instance It makes sense to name the function parameters with the same name as the struct fields, but having to repeat the `email` and `username` field names and variables is a bit tedious. If the struct had more fields, repeating each name would get even more annoying. Luckily, there’s a convenient shorthand! ### Using the Field Init Shorthand Because the parameter names and the struct field names are exactly the same in Listing 5-4, we can use the *field init shorthand* syntax to rewrite `build_user` so that it behaves exactly the same but doesn’t have the repetition of `email` and `username`, as shown in Listing 5-5. ``` struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn build_user(email: String, username: String) -> User { User { email, username, active: true, sign_in_count: 1, } } fn main() { let user1 = build_user( String::from("[email protected]"), String::from("someusername123"), ); } ``` Listing 5-5: A `build_user` function that uses field init shorthand because the `email` and `username` parameters have the same name as struct fields Here, we’re creating a new instance of the `User` struct, which has a field named `email`. We want to set the `email` field’s value to the value in the `email` parameter of the `build_user` function. Because the `email` field and the `email` parameter have the same name, we only need to write `email` rather than `email: email`. ### Creating Instances From Other Instances With Struct Update Syntax It’s often useful to create a new instance of a struct that includes most of the values from another instance, but changes some. You can do this using *struct update syntax*. First, in Listing 5-6 we show how to create a new `User` instance in `user2` regularly, without the update syntax. We set a new value for `email` but otherwise use the same values from `user1` that we created in Listing 5-2. ``` struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() { // --snip-- let user1 = User { email: String::from("[email protected]"), username: String::from("someusername123"), active: true, sign_in_count: 1, }; let user2 = User { active: user1.active, username: user1.username, email: String::from("[email protected]"), sign_in_count: user1.sign_in_count, }; } ``` Listing 5-6: Creating a new `User` instance using one of the values from `user1` Using struct update syntax, we can achieve the same effect with less code, as shown in Listing 5-7. The syntax `..` specifies that the remaining fields not explicitly set should have the same value as the fields in the given instance. ``` struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() { // --snip-- let user1 = User { email: String::from("[email protected]"), username: String::from("someusername123"), active: true, sign_in_count: 1, }; let user2 = User { email: String::from("[email protected]"), ..user1 }; } ``` Listing 5-7: Using struct update syntax to set a new `email` value for a `User` instance but use the rest of the values from `user1` The code in Listing 5-7 also creates an instance in `user2` that has a different value for `email` but has the same values for the `username`, `active`, and `sign_in_count` fields from `user1`. The `..user1` must come last to specify that any remaining fields should get their values from the corresponding fields in `user1`, but we can choose to specify values for as many fields as we want in any order, regardless of the order of the fields in the struct’s definition. Note that the struct update syntax uses `=` like an assignment; this is because it moves the data, just as we saw in the [“Ways Variables and Data Interact: Move”](ch04-01-what-is-ownership#ways-variables-and-data-interact-move) section. In this example, we can no longer use `user1` after creating `user2` because the `String` in the `username` field of `user1` was moved into `user2`. If we had given `user2` new `String` values for both `email` and `username`, and thus only used the `active` and `sign_in_count` values from `user1`, then `user1` would still be valid after creating `user2`. The types of `active` and `sign_in_count` are types that implement the `Copy` trait, so the behavior we discussed in the [“Stack-Only Data: Copy”](ch04-01-what-is-ownership#stack-only-data-copy) section would apply. ### Using Tuple Structs without Named Fields to Create Different Types Rust also supports structs that look similar to tuples, called *tuple structs*. Tuple structs have the added meaning the struct name provides but don’t have names associated with their fields; rather, they just have the types of the fields. Tuple structs are useful when you want to give the whole tuple a name and make the tuple a different type from other tuples, and when naming each field as in a regular struct would be verbose or redundant. To define a tuple struct, start with the `struct` keyword and the struct name followed by the types in the tuple. For example, here we define and use two tuple structs named `Color` and `Point`: ``` struct Color(i32, i32, i32); struct Point(i32, i32, i32); fn main() { let black = Color(0, 0, 0); let origin = Point(0, 0, 0); } ``` Note that the `black` and `origin` values are different types, because they’re instances of different tuple structs. Each struct you define is its own type, even though the fields within the struct might have the same types. For example, a function that takes a parameter of type `Color` cannot take a `Point` as an argument, even though both types are made up of three `i32` values. Otherwise, tuple struct instances are similar to tuples in that you can destructure them into their individual pieces, and you can use a `.` followed by the index to access an individual value. ### Unit-Like Structs Without Any Fields You can also define structs that don’t have any fields! These are called *unit-like structs* because they behave similarly to `()`, the unit type that we mentioned in [“The Tuple Type”](ch03-02-data-types#the-tuple-type) section. Unit-like structs can be useful when you need to implement a trait on some type but don’t have any data that you want to store in the type itself. We’ll discuss traits in Chapter 10. Here’s an example of declaring and instantiating a unit struct named `AlwaysEqual`: ``` struct AlwaysEqual; fn main() { let subject = AlwaysEqual; } ``` To define `AlwaysEqual`, we use the `struct` keyword, the name we want, then a semicolon. No need for curly brackets or parentheses! Then we can get an instance of `AlwaysEqual` in the `subject` variable in a similar way: using the name we defined, without any curly brackets or parentheses. Imagine that later we’ll implement behavior for this type such that every instance of `AlwaysEqual` is always equal to every instance of any other type, perhaps to have a known result for testing purposes. We wouldn’t need any data to implement that behavior! You’ll see in Chapter 10 how to define traits and implement them on any type, including unit-like structs. > ### Ownership of Struct Data > > In the `User` struct definition in Listing 5-1, we used the owned `String` type rather than the `&str` string slice type. This is a deliberate choice because we want each instance of this struct to own all of its data and for that data to be valid for as long as the entire struct is valid. > > It’s also possible for structs to store references to data owned by something else, but to do so requires the use of *lifetimes*, a Rust feature that we’ll discuss in Chapter 10. Lifetimes ensure that the data referenced by a struct is valid for as long as the struct is. Let’s say you try to store a reference in a struct without specifying lifetimes, like the following; this won’t work: > > Filename: src/main.rs > > > ``` > struct User { > active: bool, > username: &str, > email: &str, > sign_in_count: u64, > } > > fn main() { > let user1 = User { > email: "[email protected]", > username: "someusername123", > active: true, > sign_in_count: 1, > }; > } > > ``` > The compiler will complain that it needs lifetime specifiers: > > > ``` > $ cargo run > Compiling structs v0.1.0 (file:///projects/structs) > error[E0106]: missing lifetime specifier > --> src/main.rs:3:15 > | > 3 | username: &str, > | ^ expected named lifetime parameter > | > help: consider introducing a named lifetime parameter > | > 1 ~ struct User<'a> { > 2 | active: bool, > 3 ~ username: &'a str, > | > > error[E0106]: missing lifetime specifier > --> src/main.rs:4:12 > | > 4 | email: &str, > | ^ expected named lifetime parameter > | > help: consider introducing a named lifetime parameter > | > 1 ~ struct User<'a> { > 2 | active: bool, > 3 | username: &str, > 4 ~ email: &'a str, > | > > For more information about this error, try `rustc --explain E0106`. > error: could not compile `structs` due to 2 previous errors > > ``` > In Chapter 10, we’ll discuss how to fix these errors so you can store references in structs, but for now, we’ll fix errors like these using owned types like `String` instead of references like `&str`. > > rust Advanced Traits Advanced Traits =============== We first covered traits in the [“Traits: Defining Shared Behavior”](ch10-02-traits#traits-defining-shared-behavior) section of Chapter 10, but we didn’t discuss the more advanced details. Now that you know more about Rust, we can get into the nitty-gritty. ### Specifying Placeholder Types in Trait Definitions with Associated Types *Associated types* connect a type placeholder with a trait such that the trait method definitions can use these placeholder types in their signatures. The implementor of a trait will specify the concrete type to be used instead of the placeholder type for the particular implementation. That way, we can define a trait that uses some types without needing to know exactly what those types are until the trait is implemented. We’ve described most of the advanced features in this chapter as being rarely needed. Associated types are somewhere in the middle: they’re used more rarely than features explained in the rest of the book but more commonly than many of the other features discussed in this chapter. One example of a trait with an associated type is the `Iterator` trait that the standard library provides. The associated type is named `Item` and stands in for the type of the values the type implementing the `Iterator` trait is iterating over. The definition of the `Iterator` trait is as shown in Listing 19-12. ``` pub trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; } ``` Listing 19-12: The definition of the `Iterator` trait that has an associated type `Item` The type `Item` is a placeholder, and the `next` method’s definition shows that it will return values of type `Option<Self::Item>`. Implementors of the `Iterator` trait will specify the concrete type for `Item`, and the `next` method will return an `Option` containing a value of that concrete type. Associated types might seem like a similar concept to generics, in that the latter allow us to define a function without specifying what types it can handle. To examine the difference between the two concepts, we’ll look at an implementation of the `Iterator` trait on a type named `Counter` that specifies the `Item` type is `u32`: Filename: src/lib.rs ``` struct Counter { count: u32, } impl Counter { fn new() -> Counter { Counter { count: 0 } } } impl Iterator for Counter { type Item = u32; fn next(&mut self) -> Option<Self::Item> { // --snip-- if self.count < 5 { self.count += 1; Some(self.count) } else { None } } } ``` This syntax seems comparable to that of generics. So why not just define the `Iterator` trait with generics, as shown in Listing 19-13? ``` pub trait Iterator<T> { fn next(&mut self) -> Option<T>; } ``` Listing 19-13: A hypothetical definition of the `Iterator` trait using generics The difference is that when using generics, as in Listing 19-13, we must annotate the types in each implementation; because we can also implement `Iterator<String> for Counter` or any other type, we could have multiple implementations of `Iterator` for `Counter`. In other words, when a trait has a generic parameter, it can be implemented for a type multiple times, changing the concrete types of the generic type parameters each time. When we use the `next` method on `Counter`, we would have to provide type annotations to indicate which implementation of `Iterator` we want to use. With associated types, we don’t need to annotate types because we can’t implement a trait on a type multiple times. In Listing 19-12 with the definition that uses associated types, we can only choose what the type of `Item` will be once, because there can only be one `impl Iterator for Counter`. We don’t have to specify that we want an iterator of `u32` values everywhere that we call `next` on `Counter`. Associated types also become part of the trait’s contract: implementors of the trait must provide a type to stand in for the associated type placeholder. Associated types often have a name that describes how the type will be used, and documenting the associated type in the API documentation is good practice. ### Default Generic Type Parameters and Operator Overloading When we use generic type parameters, we can specify a default concrete type for the generic type. This eliminates the need for implementors of the trait to specify a concrete type if the default type works. You specify a default type when declaring a generic type with the `<PlaceholderType=ConcreteType>` syntax. A great example of a situation where this technique is useful is with *operator overloading*, in which you customize the behavior of an operator (such as `+`) in particular situations. Rust doesn’t allow you to create your own operators or overload arbitrary operators. But you can overload the operations and corresponding traits listed in `std::ops` by implementing the traits associated with the operator. For example, in Listing 19-14 we overload the `+` operator to add two `Point` instances together. We do this by implementing the `Add` trait on a `Point` struct: Filename: src/main.rs ``` use std::ops::Add; #[derive(Debug, Copy, Clone, PartialEq)] struct Point { x: i32, y: i32, } impl Add for Point { type Output = Point; fn add(self, other: Point) -> Point { Point { x: self.x + other.x, y: self.y + other.y, } } } fn main() { assert_eq!( Point { x: 1, y: 0 } + Point { x: 2, y: 3 }, Point { x: 3, y: 3 } ); } ``` Listing 19-14: Implementing the `Add` trait to overload the `+` operator for `Point` instances The `add` method adds the `x` values of two `Point` instances and the `y` values of two `Point` instances to create a new `Point`. The `Add` trait has an associated type named `Output` that determines the type returned from the `add` method. The default generic type in this code is within the `Add` trait. Here is its definition: ``` #![allow(unused)] fn main() { trait Add<Rhs=Self> { type Output; fn add(self, rhs: Rhs) -> Self::Output; } } ``` This code should look generally familiar: a trait with one method and an associated type. The new part is `Rhs=Self`: this syntax is called *default type parameters*. The `Rhs` generic type parameter (short for “right hand side”) defines the type of the `rhs` parameter in the `add` method. If we don’t specify a concrete type for `Rhs` when we implement the `Add` trait, the type of `Rhs` will default to `Self`, which will be the type we’re implementing `Add` on. When we implemented `Add` for `Point`, we used the default for `Rhs` because we wanted to add two `Point` instances. Let’s look at an example of implementing the `Add` trait where we want to customize the `Rhs` type rather than using the default. We have two structs, `Millimeters` and `Meters`, holding values in different units. This thin wrapping of an existing type in another struct is known as the *newtype pattern*, which we describe in more detail in the [“Using the Newtype Pattern to Implement External Traits on External Types”](ch19-03-advanced-traits#using-the-newtype-pattern-to-implement-external-traits-on-external-types) section. We want to add values in millimeters to values in meters and have the implementation of `Add` do the conversion correctly. We can implement `Add` for `Millimeters` with `Meters` as the `Rhs`, as shown in Listing 19-15. Filename: src/lib.rs ``` use std::ops::Add; struct Millimeters(u32); struct Meters(u32); impl Add<Meters> for Millimeters { type Output = Millimeters; fn add(self, other: Meters) -> Millimeters { Millimeters(self.0 + (other.0 * 1000)) } } ``` Listing 19-15: Implementing the `Add` trait on `Millimeters` to add `Millimeters` to `Meters` To add `Millimeters` and `Meters`, we specify `impl Add<Meters>` to set the value of the `Rhs` type parameter instead of using the default of `Self`. You’ll use default type parameters in two main ways: * To extend a type without breaking existing code * To allow customization in specific cases most users won’t need The standard library’s `Add` trait is an example of the second purpose: usually, you’ll add two like types, but the `Add` trait provides the ability to customize beyond that. Using a default type parameter in the `Add` trait definition means you don’t have to specify the extra parameter most of the time. In other words, a bit of implementation boilerplate isn’t needed, making it easier to use the trait. The first purpose is similar to the second but in reverse: if you want to add a type parameter to an existing trait, you can give it a default to allow extension of the functionality of the trait without breaking the existing implementation code. ### Fully Qualified Syntax for Disambiguation: Calling Methods with the Same Name Nothing in Rust prevents a trait from having a method with the same name as another trait’s method, nor does Rust prevent you from implementing both traits on one type. It’s also possible to implement a method directly on the type with the same name as methods from traits. When calling methods with the same name, you’ll need to tell Rust which one you want to use. Consider the code in Listing 19-16 where we’ve defined two traits, `Pilot` and `Wizard`, that both have a method called `fly`. We then implement both traits on a type `Human` that already has a method named `fly` implemented on it. Each `fly` method does something different. Filename: src/main.rs ``` trait Pilot { fn fly(&self); } trait Wizard { fn fly(&self); } struct Human; impl Pilot for Human { fn fly(&self) { println!("This is your captain speaking."); } } impl Wizard for Human { fn fly(&self) { println!("Up!"); } } impl Human { fn fly(&self) { println!("*waving arms furiously*"); } } fn main() {} ``` Listing 19-16: Two traits are defined to have a `fly` method and are implemented on the `Human` type, and a `fly` method is implemented on `Human` directly When we call `fly` on an instance of `Human`, the compiler defaults to calling the method that is directly implemented on the type, as shown in Listing 19-17. Filename: src/main.rs ``` trait Pilot { fn fly(&self); } trait Wizard { fn fly(&self); } struct Human; impl Pilot for Human { fn fly(&self) { println!("This is your captain speaking."); } } impl Wizard for Human { fn fly(&self) { println!("Up!"); } } impl Human { fn fly(&self) { println!("*waving arms furiously*"); } } fn main() { let person = Human; person.fly(); } ``` Listing 19-17: Calling `fly` on an instance of `Human` Running this code will print `*waving arms furiously*`, showing that Rust called the `fly` method implemented on `Human` directly. To call the `fly` methods from either the `Pilot` trait or the `Wizard` trait, we need to use more explicit syntax to specify which `fly` method we mean. Listing 19-18 demonstrates this syntax. Filename: src/main.rs ``` trait Pilot { fn fly(&self); } trait Wizard { fn fly(&self); } struct Human; impl Pilot for Human { fn fly(&self) { println!("This is your captain speaking."); } } impl Wizard for Human { fn fly(&self) { println!("Up!"); } } impl Human { fn fly(&self) { println!("*waving arms furiously*"); } } fn main() { let person = Human; Pilot::fly(&person); Wizard::fly(&person); person.fly(); } ``` Listing 19-18: Specifying which trait’s `fly` method we want to call Specifying the trait name before the method name clarifies to Rust which implementation of `fly` we want to call. We could also write `Human::fly(&person)`, which is equivalent to the `person.fly()` that we used in Listing 19-18, but this is a bit longer to write if we don’t need to disambiguate. Running this code prints the following: ``` $ cargo run Compiling traits-example v0.1.0 (file:///projects/traits-example) Finished dev [unoptimized + debuginfo] target(s) in 0.46s Running `target/debug/traits-example` This is your captain speaking. Up! *waving arms furiously* ``` Because the `fly` method takes a `self` parameter, if we had two *types* that both implement one *trait*, Rust could figure out which implementation of a trait to use based on the type of `self`. However, associated functions that are not methods don’t have a `self` parameter. When there are multiple types or traits that define non-method functions with the same function name, Rust doesn't always know which type you mean unless you use *fully qualified syntax*. For example, in Listing 19-19 we create a trait for an animal shelter that wants to name all baby dogs *Spot*. We make an `Animal` trait with an associated non-method function `baby_name`. The `Animal` trait is implemented for the struct `Dog`, on which we also provide an associated non-method function `baby_name` directly. Filename: src/main.rs ``` trait Animal { fn baby_name() -> String; } struct Dog; impl Dog { fn baby_name() -> String { String::from("Spot") } } impl Animal for Dog { fn baby_name() -> String { String::from("puppy") } } fn main() { println!("A baby dog is called a {}", Dog::baby_name()); } ``` Listing 19-19: A trait with an associated function and a type with an associated function of the same name that also implements the trait We implement the code for naming all puppies Spot in the `baby_name` associated function that is defined on `Dog`. The `Dog` type also implements the trait `Animal`, which describes characteristics that all animals have. Baby dogs are called puppies, and that is expressed in the implementation of the `Animal` trait on `Dog` in the `baby_name` function associated with the `Animal` trait. In `main`, we call the `Dog::baby_name` function, which calls the associated function defined on `Dog` directly. This code prints the following: ``` $ cargo run Compiling traits-example v0.1.0 (file:///projects/traits-example) Finished dev [unoptimized + debuginfo] target(s) in 0.54s Running `target/debug/traits-example` A baby dog is called a Spot ``` This output isn’t what we wanted. We want to call the `baby_name` function that is part of the `Animal` trait that we implemented on `Dog` so the code prints `A baby dog is called a puppy`. The technique of specifying the trait name that we used in Listing 19-18 doesn’t help here; if we change `main` to the code in Listing 19-20, we’ll get a compilation error. Filename: src/main.rs ``` trait Animal { fn baby_name() -> String; } struct Dog; impl Dog { fn baby_name() -> String { String::from("Spot") } } impl Animal for Dog { fn baby_name() -> String { String::from("puppy") } } fn main() { println!("A baby dog is called a {}", Animal::baby_name()); } ``` Listing 19-20: Attempting to call the `baby_name` function from the `Animal` trait, but Rust doesn’t know which implementation to use Because `Animal::baby_name` doesn’t have a `self` parameter, and there could be other types that implement the `Animal` trait, Rust can’t figure out which implementation of `Animal::baby_name` we want. We’ll get this compiler error: ``` $ cargo run Compiling traits-example v0.1.0 (file:///projects/traits-example) error[E0283]: type annotations needed --> src/main.rs:20:43 | 20 | println!("A baby dog is called a {}", Animal::baby_name()); | ^^^^^^^^^^^^^^^^^ cannot infer type | = note: cannot satisfy `_: Animal` For more information about this error, try `rustc --explain E0283`. error: could not compile `traits-example` due to previous error ``` To disambiguate and tell Rust that we want to use the implementation of `Animal` for `Dog` as opposed to the implementation of `Animal` for some other type, we need to use fully qualified syntax. Listing 19-21 demonstrates how to use fully qualified syntax. Filename: src/main.rs ``` trait Animal { fn baby_name() -> String; } struct Dog; impl Dog { fn baby_name() -> String { String::from("Spot") } } impl Animal for Dog { fn baby_name() -> String { String::from("puppy") } } fn main() { println!("A baby dog is called a {}", <Dog as Animal>::baby_name()); } ``` Listing 19-21: Using fully qualified syntax to specify that we want to call the `baby_name` function from the `Animal` trait as implemented on `Dog` We’re providing Rust with a type annotation within the angle brackets, which indicates we want to call the `baby_name` method from the `Animal` trait as implemented on `Dog` by saying that we want to treat the `Dog` type as an `Animal` for this function call. This code will now print what we want: ``` $ cargo run Compiling traits-example v0.1.0 (file:///projects/traits-example) Finished dev [unoptimized + debuginfo] target(s) in 0.48s Running `target/debug/traits-example` A baby dog is called a puppy ``` In general, fully qualified syntax is defined as follows: ``` <Type as Trait>::function(receiver_if_method, next_arg, ...); ``` For associated functions that aren’t methods, there would not be a `receiver`: there would only be the list of other arguments. You could use fully qualified syntax everywhere that you call functions or methods. However, you’re allowed to omit any part of this syntax that Rust can figure out from other information in the program. You only need to use this more verbose syntax in cases where there are multiple implementations that use the same name and Rust needs help to identify which implementation you want to call. ### Using Supertraits to Require One Trait’s Functionality Within Another Trait Sometimes, you might write a trait definition that depends on another trait: for a type to implement the first trait, you want to require that type to also implement the second trait. You would do this so that your trait definition can make use of the associated items of the second trait. The trait your trait definition is relying on is called a *supertrait* of your trait. For example, let’s say we want to make an `OutlinePrint` trait with an `outline_print` method that will print a given value formatted so that it's framed in asterisks. That is, given a `Point` struct that implements the standard library trait `Display` to result in `(x, y)`, when we call `outline_print` on a `Point` instance that has `1` for `x` and `3` for `y`, it should print the following: ``` ********** * * * (1, 3) * * * ********** ``` In the implementation of the `outline_print` method, we want to use the `Display` trait’s functionality. Therefore, we need to specify that the `OutlinePrint` trait will work only for types that also implement `Display` and provide the functionality that `OutlinePrint` needs. We can do that in the trait definition by specifying `OutlinePrint: Display`. This technique is similar to adding a trait bound to the trait. Listing 19-22 shows an implementation of the `OutlinePrint` trait. Filename: src/main.rs ``` use std::fmt; trait OutlinePrint: fmt::Display { fn outline_print(&self) { let output = self.to_string(); let len = output.len(); println!("{}", "*".repeat(len + 4)); println!("*{}*", " ".repeat(len + 2)); println!("* {} *", output); println!("*{}*", " ".repeat(len + 2)); println!("{}", "*".repeat(len + 4)); } } fn main() {} ``` Listing 19-22: Implementing the `OutlinePrint` trait that requires the functionality from `Display` Because we’ve specified that `OutlinePrint` requires the `Display` trait, we can use the `to_string` function that is automatically implemented for any type that implements `Display`. If we tried to use `to_string` without adding a colon and specifying the `Display` trait after the trait name, we’d get an error saying that no method named `to_string` was found for the type `&Self` in the current scope. Let’s see what happens when we try to implement `OutlinePrint` on a type that doesn’t implement `Display`, such as the `Point` struct: Filename: src/main.rs ``` use std::fmt; trait OutlinePrint: fmt::Display { fn outline_print(&self) { let output = self.to_string(); let len = output.len(); println!("{}", "*".repeat(len + 4)); println!("*{}*", " ".repeat(len + 2)); println!("* {} *", output); println!("*{}*", " ".repeat(len + 2)); println!("{}", "*".repeat(len + 4)); } } struct Point { x: i32, y: i32, } impl OutlinePrint for Point {} fn main() { let p = Point { x: 1, y: 3 }; p.outline_print(); } ``` We get an error saying that `Display` is required but not implemented: ``` $ cargo run Compiling traits-example v0.1.0 (file:///projects/traits-example) error[E0277]: `Point` doesn't implement `std::fmt::Display` --> src/main.rs:20:6 | 20 | impl OutlinePrint for Point {} | ^^^^^^^^^^^^ `Point` cannot be formatted with the default formatter | = help: the trait `std::fmt::Display` is not implemented for `Point` = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead note: required by a bound in `OutlinePrint` --> src/main.rs:3:21 | 3 | trait OutlinePrint: fmt::Display { | ^^^^^^^^^^^^ required by this bound in `OutlinePrint` For more information about this error, try `rustc --explain E0277`. error: could not compile `traits-example` due to previous error ``` To fix this, we implement `Display` on `Point` and satisfy the constraint that `OutlinePrint` requires, like so: Filename: src/main.rs ``` trait OutlinePrint: fmt::Display { fn outline_print(&self) { let output = self.to_string(); let len = output.len(); println!("{}", "*".repeat(len + 4)); println!("*{}*", " ".repeat(len + 2)); println!("* {} *", output); println!("*{}*", " ".repeat(len + 2)); println!("{}", "*".repeat(len + 4)); } } struct Point { x: i32, y: i32, } impl OutlinePrint for Point {} use std::fmt; impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) } } fn main() { let p = Point { x: 1, y: 3 }; p.outline_print(); } ``` Then implementing the `OutlinePrint` trait on `Point` will compile successfully, and we can call `outline_print` on a `Point` instance to display it within an outline of asterisks. ### Using the Newtype Pattern to Implement External Traits on External Types In Chapter 10 in the [“Implementing a Trait on a Type”](ch10-02-traits#implementing-a-trait-on-a-type) section, we mentioned the orphan rule that states we’re only allowed to implement a trait on a type if either the trait or the type are local to our crate. It’s possible to get around this restriction using the *newtype pattern*, which involves creating a new type in a tuple struct. (We covered tuple structs in the [“Using Tuple Structs without Named Fields to Create Different Types”](ch05-01-defining-structs#using-tuple-structs-without-named-fields-to-create-different-types) section of Chapter 5.) The tuple struct will have one field and be a thin wrapper around the type we want to implement a trait for. Then the wrapper type is local to our crate, and we can implement the trait on the wrapper. *Newtype* is a term that originates from the Haskell programming language. There is no runtime performance penalty for using this pattern, and the wrapper type is elided at compile time. As an example, let’s say we want to implement `Display` on `Vec<T>`, which the orphan rule prevents us from doing directly because the `Display` trait and the `Vec<T>` type are defined outside our crate. We can make a `Wrapper` struct that holds an instance of `Vec<T>`; then we can implement `Display` on `Wrapper` and use the `Vec<T>` value, as shown in Listing 19-23. Filename: src/main.rs ``` use std::fmt; struct Wrapper(Vec<String>); impl fmt::Display for Wrapper { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{}]", self.0.join(", ")) } } fn main() { let w = Wrapper(vec![String::from("hello"), String::from("world")]); println!("w = {}", w); } ``` Listing 19-23: Creating a `Wrapper` type around `Vec<String>` to implement `Display` The implementation of `Display` uses `self.0` to access the inner `Vec<T>`, because `Wrapper` is a tuple struct and `Vec<T>` is the item at index 0 in the tuple. Then we can use the functionality of the `Display` type on `Wrapper`. The downside of using this technique is that `Wrapper` is a new type, so it doesn’t have the methods of the value it’s holding. We would have to implement all the methods of `Vec<T>` directly on `Wrapper` such that the methods delegate to `self.0`, which would allow us to treat `Wrapper` exactly like a `Vec<T>`. If we wanted the new type to have every method the inner type has, implementing the `Deref` trait (discussed in Chapter 15 in the [“Treating Smart Pointers Like Regular References with the `Deref` Trait”](ch15-02-deref#treating-smart-pointers-like-regular-references-with-the-deref-trait) section) on the `Wrapper` to return the inner type would be a solution. If we don’t want the `Wrapper` type to have all the methods of the inner type—for example, to restrict the `Wrapper` type’s behavior—we would have to implement just the methods we do want manually. This newtype pattern is also useful even when traits are not involved. Let’s switch focus and look at some advanced ways to interact with Rust’s type system.
programming_docs