Variable sized arrays / Vectors
let mut vec: Vec<T> = Vec::new();
= Vec::with_capacity();
= vec![];
= boxedarray.into_vec()
= Vec::from(slice|str|VecDeque|CString)
= othervec.clone();
if T:Clone


Accessing
vec[3];
vec[1..3], vec[..3], vec[3..], vec[..]; vec[2] = a;
vec.len();
.is_empty();
.first_mut(); .last_mut();
-> Option
.get_mut(index);
-> Option
.contains(needle);
-> bool
.iter().find(|&T| -> bool);
-> Option
.binary_search(x:&T);
-> Result<usize, usize>
Ok(i): pos, Err(i): pos for insertion
.binary_search_by(|&T|->Ordering);
.binary_search_by_key(Key, |&T|->Key);
.ends_with(needle);
.starts_with(needle);


Adding
.push(3);
to end
.insert(index, element);
.extend(iterable);
.extend_from_slice(&[T]);
.append(other : Vec);
drains other
.clone_from(&Vec<T>);
overrides self, if T:Clone
.clone_from_slice(&[T]);
if T:Clone
.copy_from_slice(&[T]);
if T:Copy (use memcpy)


Removing
.pop();
removes last -> Option
.remove(index);
-> el, shifts left
.swap_remove(index);
-> el, fills with last
.truncate(i);
cut until .len() = i
.drain(range);
-> iter that drains
.clear();
.retain(|i| -> bool);
in place
.dedup();
removes duplicates (if T:PartialEq)


Manipulating
.sort();
in place
.sort_by(|&T|->Ordering);
in place
.sort_by_key(|&T|->Key);
Key:Ordering
.reverse();
in place
.swap(index1, index2);


Transforming (Iter, as_, to_)
.iter_mut();
->&mut T, keeps vector
.into_iter();
->T, consumes vector
.chunks_mut(cnk_sz);
-> iter over a non overlapping slice at a time
.windows(wnd_sz);
-> iter over an overlapping slice at a time


.into_boxed_slice();
-> Box<T>
.as_ref();
-> &[T] or &Vec<T>
.to_vec();
like clone(), if T:Clone
.as_mut_slice();
-> &mut[T]


Memory
.capacity();
.reserve(100);
in addition to .len() or more
.reserve_exact(100);
in addition to .len()
.shrink_to_fit();


Split
.split_at_mut(mid);
-> (p1, p2), [mid] in 2nd part
.split_mut(|&T| -> bool);
.splitn_mut(n, |&T| -> bool); .rsplitn_mut(_);
-> iter over mutable subslices,
seperated by ||->true, at most n times
.split_off(mid);
-> Vec; [mid] in 2nd part


Comparision
.cmp() .eq() .ne();
T: PartialEq
.lt() .le() .gt() .ge();
if T:PartialOrd


.hash(state: Hasher)
if T:Hash


Traits
From<BinaryHeap> from() | BorrowMut borrow /_mut() | Clone clone/_from() | Hash hash/_slice() | IndexMut index/_mut() DerefMut deref/_mut() | FromIterator from_iter() | IntoIterator into_iter() | Extend extend() | PartialEq eq() ne() | PartialOrd partial_cmp() lt() le() gt() ge() | Eq | Ord cmp() | Drop drop() | Default default() | Debug (if T:Debug) fmt() | AsRef AsMut as_ref() as_mut() | From from() | Write write() write_all() flush() by_ref() .. |
Hashmaps / Dicts
use std::collections::HashMap;
let mut foo: HashMap<K, V> = HashMap::new();
= HashMap::with_capacity();
K: Eq, Hash
= other.clone();
if V,K:Clone


Access
foo[key];
foo.len();
.iter_mut();
-> iter over (&K, &mut V)
.into_iter();
-> IterMut
.keys();
-> iter over keys
.values_mut();
-> iter over values
.is_empty();
-> bool
.contains_key(k:Q);
-> bool


Manipulate
.get_mut(k:&Q);
-> Option<&V>, K:Borrow<Q>
.entry(key);
in place manipulation
.drain();
-> iter that drains
.clear();
.extend(iter : <Item=(&K,&V)>);
.insert(k,v);
-> Option<&V>, None on success.
.remove(k:&Q);
-> Option<&V>
.from_iter(iter : <Item=(K,V)>);
-> HashMap


Manage
.capacity();
.reserve(additional);
.shrink_to_fit();
.clone_from(source);
overrides self


Comparision
.eq() .ne();
T: PartialEq


Special Hasher
let hm = HashMap::with_hasher(b);
= HashMap::with_capacity_and_hasher(b);
hm.hasher(b);
-> &BuildHasher


Traits
Clone clone() clone_from() | PartialEq eq() ne() | Eq | Debug fmt() | Default default() | Index index() | IntoIterator into_iter() | FromIterator from_iter() | Extend extend() |
Option
let foo : Option = Some(T::new());
= None;


If
.is_some();
.is_none();


&
.as_ref();
-> Option<&T>
.as_mut();
-> Option<&mut T>
.cloned();
Option<&T> -> Option<T> if T:Clone
.iter_mut();
Iter with 1 or 0 elements


Retrieve T
.unwrap();
-> T or panic
.expect(msg);
-> T or panic(msg)
.unwrap_or(default:T);
-> T
.unwrap_or_default();
-> T, if T:Default
.unwrap_or_else(|| -> T);
-> T
mutableopt.take();
-> Option<T>, moves T out of mutableopt


Manipulate (map)
.map(|t| -> U);
-> Option<U>
.map_or(default:U, |t| -> U);
-> Option<U>
.map_or_else(|| default -> U, |t| -> U);
-> Option<U>


to Result<>
.ok_or(err:E);
-> Result<T,E>
.ok_or_else(|| err -> E);
-> Result<T,E>


Boolean Combinations
a.and(b : Option<U>);
b if a && b
a.and_then(|| b -> Option<U>);
b if a && b
a.or(b : Option<T>);
a if a else b
a.or_else(|| b -> Option<T>);
a if a else b


Traits
Hash hash() | Debug fmt() | Ord cmp() | Eq | PartialOrd partial_cmp() lt() le() gt() ge() | PartialEq eq() ne() | Copy | Clone clone() clone_from() | Default default() | IntoIterator into_iter() | FromIterator from_iter() |
Result
let foo : Result = Ok(T::new());
= Err(E::new());


If
.is_ok();
.is_err();


&
.as_ref();
-> Result<&T, &E>
.as_mut();
-> Option<&mut T, &mut E>
.iter_mut();
Iter with 1 or 0 elements


Retrieve T
.unwrap();
-> T or panic; if E:Debug
.expect(msg);
-> T or panic(msg); if E:Debug
.unwrap_or(default:T);
-> T
.unwrap_or_else(|err| default -> T);
-> T


Retrieve E
.unwrap_err();
-> E; if T:Debug


Manipulate (map)
.map(|t| -> U);
-> Result<U,E>
.map_err(|e| -> F);
-> Result<T,F>


to Option<>
.ok();
-> Option<T>
.err();
-> Option<E>


Boolean Combinations
a.and(b : Result<U,E>);
b if a && b else first err
a.and_then(|| b -> Result<U,E>);
b if a && b else first error
a.or(b : Result<T,E>);
a if a else b
a.or_else(|| b -> Result<T,E>);
a if a else b


Traits
Hash hash() | Debug fmt() | Ord cmp() | Eq | PartialOrd partial_cmp() lt() le() gt() ge() | PartialEq eq() ne() | Copy | Clone clone() clone_from() | IntoIterator into_iter() | FromIterator from_iter() |
Rust Cheatsheet

Contribute at github.com/phaiax/rust-cheatsheet

Creative Commons License
This work is licensed under a
Creative Commons Attribution-
ShareAlike 4.0 International License
.

A contiguous growable array type, written Vec<T> but pronounced 'vector.'

Examples

fn main() { let mut vec = Vec::new(); vec.push(1); vec.push(2); assert_eq!(vec.len(), 2); assert_eq!(vec[0], 1); assert_eq!(vec.pop(), Some(2)); assert_eq!(vec.len(), 1); vec[0] = 7; assert_eq!(vec[0], 7); vec.extend([1, 2, 3].iter().cloned()); for x in &vec { println!("{}", x); } assert_eq!(vec, [7, 1, 2, 3]); }
let mut vec = Vec::new();
vec.push(1);
vec.push(2);

assert_eq!(vec.len(), 2);
assert_eq!(vec[0], 1);

assert_eq!(vec.pop(), Some(2));
assert_eq!(vec.len(), 1);

vec[0] = 7;
assert_eq!(vec[0], 7);

vec.extend([1, 2, 3].iter().cloned());

for x in &vec {
    println!("{}", x);
}
assert_eq!(vec, [7, 1, 2, 3]);

The vec! macro is provided to make initialization more convenient:

fn main() { let mut vec = vec![1, 2, 3]; vec.push(4); assert_eq!(vec, [1, 2, 3, 4]); }
let mut vec = vec![1, 2, 3];
vec.push(4);
assert_eq!(vec, [1, 2, 3, 4]);

It can also initialize each element of a Vec<T> with a given value:

fn main() { let vec = vec![0; 5]; assert_eq!(vec, [0, 0, 0, 0, 0]); }
let vec = vec![0; 5];
assert_eq!(vec, [0, 0, 0, 0, 0]);

Use a Vec<T> as an efficient stack:

fn main() { let mut stack = Vec::new(); stack.push(1); stack.push(2); stack.push(3); while let Some(top) = stack.pop() { // Prints 3, 2, 1 println!("{}", top); } }
let mut stack = Vec::new();

stack.push(1);
stack.push(2);
stack.push(3);

while let Some(top) = stack.pop() {
    // Prints 3, 2, 1
    println!("{}", top);
}

Indexing

The Vec type allows to access values by index, because it implements the Index trait. An example will be more explicit:

fn main() { let v = vec!(0, 2, 4, 6); println!("{}", v[1]); // it will display '2' }
let v = vec!(0, 2, 4, 6);
println!("{}", v[1]); // it will display '2'

However be careful: if you try to access an index which isn't in the Vec, your software will panic! You cannot do this:

fn main() { let v = vec!(0, 2, 4, 6); println!("{}", v[6]); // it will panic! }
let v = vec!(0, 2, 4, 6);
println!("{}", v[6]); // it will panic!

In conclusion: always check if the index you want to get really exists before doing it.

Slicing

A Vec can be mutable. Slices, on the other hand, are read-only objects. To get a slice, use "&". Example:

fn main() { fn read_slice(slice: &[usize]) { // ... } let v = vec!(0, 1); read_slice(&v); // ... and that's all! // you can also do it like this: let x : &[usize] = &v; }
fn read_slice(slice: &[usize]) {
    // ...
}

let v = vec!(0, 1);
read_slice(&v);

// ... and that's all!
// you can also do it like this:
let x : &[usize] = &v;

In Rust, it's more common to pass slices as arguments rather than vectors when you just want to provide a read access. The same goes for String and &str.

Capacity and reallocation

The capacity of a vector is the amount of space allocated for any future elements that will be added onto the vector. This is not to be confused with the length of a vector, which specifies the number of actual elements within the vector. If a vector's length exceeds its capacity, its capacity will automatically be increased, but its elements will have to be reallocated.

For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10 more elements. Pushing 10 or fewer elements onto the vector will not change its capacity or cause reallocation to occur. However, if the vector's length is increased to 11, it will have to reallocate, which can be slow. For this reason, it is recommended to use Vec::with_capacity whenever possible to specify how big the vector is expected to get.

Guarantees

Due to its incredibly fundamental nature, Vec makes a lot of guarantees about its design. This ensures that it's as low-overhead as possible in the general case, and can be correctly manipulated in primitive ways by unsafe code. Note that these guarantees refer to an unqualified Vec<T>. If additional type parameters are added (e.g. to support custom allocators), overriding their defaults may change the behavior.

Most fundamentally, Vec is and always will be a (pointer, capacity, length) triplet. No more, no less. The order of these fields is completely unspecified, and you should use the appropriate methods to modify these. The pointer will never be null, so this type is null-pointer-optimized.

However, the pointer may not actually point to allocated memory. In particular, if you construct a Vec with capacity 0 via Vec::new(), vec![], Vec::with_capacity(0), or by calling shrink_to_fit() on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized types inside a Vec, it will not allocate space for them. Note that in this case the Vec may not report a capacity() of 0. Vec will allocate if and only if mem::size_of::<T>() * capacity() > 0. In general, Vec's allocation details are subtle enough that it is strongly recommended that you only free memory allocated by a Vec by creating a new Vec and dropping it.

If a Vec has allocated memory, then the memory it points to is on the heap (as defined by the allocator Rust is configured to use by default), and its pointer points to len() initialized elements in order (what you would see if you coerced it to a slice), followed by capacity() - len() logically uninitialized elements.

Vec will never perform a "small optimization" where elements are actually stored on the stack for two reasons:

  • It would make it more difficult for unsafe code to correctly manipulate a Vec. The contents of a Vec wouldn't have a stable address if it were only moved, and it would be more difficult to determine if a Vec had actually allocated memory.

  • It would penalize the general case, incurring an additional branch on every access.

Vec will never automatically shrink itself, even if completely empty. This ensures no unnecessary allocations or deallocations occur. Emptying a Vec and then filling it back up to the same len() should incur no calls to the allocator. If you wish to free up unused memory, use shrink_to_fit.

push and insert will never (re)allocate if the reported capacity is sufficient. push and insert will (re)allocate if len() == capacity(). That is, the reported capacity is completely accurate, and can be relied on. It can even be used to manually free the memory allocated by a Vec if desired. Bulk insertion methods may reallocate, even when not necessary.

Vec does not guarantee any particular growth strategy when reallocating when full, nor when reserve is called. The current strategy is basic and it may prove desirable to use a non-constant growth factor. Whatever strategy is used will of course guarantee O(1) amortized push.

vec![x; n], vec![a, b, c, d], and Vec::with_capacity(n), will all produce a Vec with exactly the requested capacity. If len() == capacity(), (as is the case for the vec! macro), then a Vec<T> can be converted to and from a Box<[T]> without reallocating or moving the elements.

Vec will not specifically overwrite any data that is removed from it, but also won't specifically preserve it. Its uninitialized memory is scratch space that it may use however it wants. It will generally just do whatever is most efficient or otherwise easy to implement. Do not rely on removed data to be erased for security purposes. Even if you drop a Vec, its buffer may simply be reused by another Vec. Even if you zero a Vec's memory first, that may not actually happen because the optimizer does not consider this a side-effect that must be preserved.

Vec does not currently guarantee the order in which elements are dropped (the order has changed in the past, and may change again).

fn new() -> Vec<T>

Constructs a new, empty Vec<T>.

The vector will not allocate until elements are pushed onto it.

Examples

fn main() { #![allow(unused_mut)] let mut vec: Vec<i32> = Vec::new(); }
let mut vec: Vec<i32> = Vec::new();

fn with_capacity(capacity: usize) -> Vec<T>

Constructs a new, empty Vec<T> with the specified capacity.

The vector will be able to hold exactly capacity elements without reallocating. If capacity is 0, the vector will not allocate.

It is important to note that this function does not specify the length of the returned vector, but only the capacity. (For an explanation of the difference between length and capacity, see the main Vec<T> docs above, 'Capacity and reallocation'.)

Examples

fn main() { let mut vec = Vec::with_capacity(10); // The vector contains no items, even though it has capacity for more assert_eq!(vec.len(), 0); // These are all done without reallocating... for i in 0..10 { vec.push(i); } // ...but this may make the vector reallocate vec.push(11); }
let mut vec = Vec::with_capacity(10);

// The vector contains no items, even though it has capacity for more
assert_eq!(vec.len(), 0);

// These are all done without reallocating...
for i in 0..10 {
    vec.push(i);
}

// ...but this may make the vector reallocate
vec.push(11);

fn into_vec(self: Box<[T]>) -> Vec<T>

Converts self into a vector without clones or allocation.

fn from(s: &'a [T]) -> Vec<T>

Performs the conversion.

fn from(s: &'a str) -> Vec<u8>

Performs the conversion.

fn from(other: VecDeque<T>) -> Vec<T>

Performs the conversion.

fn from(s: CString) -> Vec<u8>

Performs the conversion.

fn clone(&self) -> Vec<T>

Returns a copy of the value. Read more

Indexing

The Vec type allows to access values by index, because it implements the Index trait. An example will be more explicit:

fn main() { let v = vec!(0, 2, 4, 6); println!("{}", v[1]); // it will display '2' }
let v = vec!(0, 2, 4, 6);
println!("{}", v[1]); // it will display '2'

However be careful: if you try to access an index which isn't in the Vec, your software will panic! You cannot do this:

fn main() { let v = vec!(0, 2, 4, 6); println!("{}", v[6]); // it will panic! }
let v = vec!(0, 2, 4, 6);
println!("{}", v[6]); // it will panic!

In conclusion: always check if the index you want to get really exists before doing it.

fn len(&self) -> usize

Returns the number of elements in the vector.

Examples

fn main() { let a = vec![1, 2, 3]; assert_eq!(a.len(), 3); }
let a = vec![1, 2, 3];
assert_eq!(a.len(), 3);

fn is_empty(&self) -> bool

Returns true if the vector contains no elements.

Examples

fn main() { let mut v = Vec::new(); assert!(v.is_empty()); v.push(1); assert!(!v.is_empty()); }
let mut v = Vec::new();
assert!(v.is_empty());

v.push(1);
assert!(!v.is_empty());

fn first(&self) -> Option<&T>

Returns the first element of a slice, or None if it is empty.

Examples

fn main() { let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); }
let v = [10, 40, 30];
assert_eq!(Some(&10), v.first());

let w: &[i32] = &[];
assert_eq!(None, w.first());

fn first_mut(&mut self) -> Option<&mut T>

Returns a mutable pointer to the first element of a slice, or None if it is empty

fn last(&self) -> Option<&T>

Returns the last element of a slice, or None if it is empty.

Examples

fn main() { let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); }
let v = [10, 40, 30];
assert_eq!(Some(&30), v.last());

let w: &[i32] = &[];
assert_eq!(None, w.last());

fn last_mut(&mut self) -> Option<&mut T>

Returns a mutable pointer to the last item in the slice.

fn get(&self, index: usize) -> Option<&T>

Returns the element of a slice at the given index, or None if the index is out of bounds.

Examples

fn main() { let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(None, v.get(3)); }
let v = [10, 40, 30];
assert_eq!(Some(&40), v.get(1));
assert_eq!(None, v.get(3));

fn get_mut(&mut self, index: usize) -> Option<&mut T>

Returns a mutable reference to the element at the given index, or None if the index is out of bounds

fn contains(&self, x: &T) -> bool where T: PartialEq<T>

Returns true if the slice contains an element with the given value.

Examples

fn main() { let v = [10, 40, 30]; assert!(v.contains(&30)); assert!(!v.contains(&50)); }
let v = [10, 40, 30];
assert!(v.contains(&30));
assert!(!v.contains(&50));

fn binary_search_by<F>(&self, f: F) -> Result<usizeusize> where F: FnMut(&T) -> Ordering

Binary search a sorted slice with a comparator function.

The comparator function should implement an order consistent with the sort order of the underlying slice, returning an order code that indicates whether its argument is Less, Equal or Greater the desired target.

If a matching value is found then returns Ok, containing the index for the matched element; if no match is found then Err is returned, containing the index where a matching element could be inserted while maintaining sorted order.

Example

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].

fn main() { let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let seek = 13; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9)); let seek = 4; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7)); let seek = 100; assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13)); let seek = 1; let r = s.binary_search_by(|probe| probe.cmp(&seek)); assert!(match r { Ok(1...4) => true, _ => false, }); }
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];

let seek = 13;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
let seek = 4;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
let seek = 100;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
let seek = 1;
let r = s.binary_search_by(|probe| probe.cmp(&seek));
assert!(match r { Ok(1...4) => true, _ => false, });

fn binary_search_by_key<B, F>(&self, b: &B, f: F) -> Result<usizeusize> where B: Ord, F: FnMut(&T) -> B
1.10.0

Binary search a sorted slice with a key extraction function.

Assumes that the slice is sorted by the key, for instance with sort_by_key using the same key extraction function.

If a matching value is found then returns Ok, containing the index for the matched element; if no match is found then Err is returned, containing the index where a matching element could be inserted while maintaining sorted order.

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].

fn main() { let s = [(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)]; assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9)); assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7)); assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13)); let r = s.binary_search_by_key(&1, |&(a,b)| b); assert!(match r { Ok(1...4) => true, _ => false, }); }
let s = [(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)];

assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b),  Ok(9));
assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b),   Err(7));
assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
let r = s.binary_search_by_key(&1, |&(a,b)| b);
assert!(match r { Ok(1...4) => true, _ => false, });

fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq<T>

Returns true if needle is a suffix of the slice.

Examples

fn main() { let v = [10, 40, 30]; assert!(v.ends_with(&[30])); assert!(v.ends_with(&[40, 30])); assert!(!v.ends_with(&[50])); assert!(!v.ends_with(&[50, 30])); }
let v = [10, 40, 30];
assert!(v.ends_with(&[30]));
assert!(v.ends_with(&[40, 30]));
assert!(!v.ends_with(&[50]));
assert!(!v.ends_with(&[50, 30]));

fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq<T>

Returns true if needle is a prefix of the slice.

Examples

fn main() { let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); }
let v = [10, 40, 30];
assert!(v.starts_with(&[10]));
assert!(v.starts_with(&[10, 40]));
assert!(!v.starts_with(&[50]));
assert!(!v.starts_with(&[10, 50]));

fn push(&mut self, value: T)

Appends an element to the back of a collection.

Panics

Panics if the number of elements in the vector overflows a usize.

Examples

fn main() { let mut vec = vec![1, 2]; vec.push(3); assert_eq!(vec, [1, 2, 3]); }
let mut vec = vec![1, 2];
vec.push(3);
assert_eq!(vec, [1, 2, 3]);

fn insert(&mut self, index: usize, element: T)

Inserts an element at position index within the vector, shifting all elements after it to the right.

Panics

Panics if index is greater than the vector's length.

Examples

fn main() { let mut vec = vec![1, 2, 3]; vec.insert(1, 4); assert_eq!(vec, [1, 4, 2, 3]); vec.insert(4, 5); assert_eq!(vec, [1, 4, 2, 3, 5]); }
let mut vec = vec![1, 2, 3];
vec.insert(1, 4);
assert_eq!(vec, [1, 4, 2, 3]);
vec.insert(4, 5);
assert_eq!(vec, [1, 4, 2, 3, 5]);

fn extend<I>(&mut self, iter: I) where I: IntoIterator<Item=T>

Extends a collection with the contents of an iterator. Read more

fn extend_from_slice(&mut self, other: &[T])
1.6.0

Clones and appends all elements in a slice to the Vec.

Iterates over the slice other, clones each element, and then appends it to this Vec. The other vector is traversed in-order.

Note that this function is same as extend except that it is specialized to work with slices instead. If and when Rust gets specialization this function will likely be deprecated (but still available).

Examples

fn main() { let mut vec = vec![1]; vec.extend_from_slice(&[2, 3, 4]); assert_eq!(vec, [1, 2, 3, 4]); }
let mut vec = vec![1];
vec.extend_from_slice(&[2, 3, 4]);
assert_eq!(vec, [1, 2, 3, 4]);

fn append(&mut self, other: &mut Vec<T>)
1.4.0

Moves all the elements of other into Self, leaving other empty.

Panics

Panics if the number of elements in the vector overflows a usize.

Examples

fn main() { let mut vec = vec![1, 2, 3]; let mut vec2 = vec![4, 5, 6]; vec.append(&mut vec2); assert_eq!(vec, [1, 2, 3, 4, 5, 6]); assert_eq!(vec2, []); }
let mut vec = vec![1, 2, 3];
let mut vec2 = vec![4, 5, 6];
vec.append(&mut vec2);
assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
assert_eq!(vec2, []);

fn clone_from(&mut self, other: &Vec<T>)

Performs copy-assignment from source. Read more

fn clone_from_slice(&mut self, src: &[T]) where T: Clone
1.7.0

Copies the elements from src into self.

The length of this slice must be the same as the slice passed in.

Panics

This function will panic if the two slices have different lengths.

Example

fn main() { let mut dst = [0, 0, 0]; let src = [1, 2, 3]; dst.clone_from_slice(&src); assert!(dst == [1, 2, 3]); }
let mut dst = [0, 0, 0];
let src = [1, 2, 3];

dst.clone_from_slice(&src);
assert!(dst == [1, 2, 3]);

fn copy_from_slice(&mut self, src: &[T]) where T: Copy
1.9.0

Copies all elements from src into self, using a memcpy.

The length of src must be the same as self.

Panics

This function will panic if the two slices have different lengths.

Example

fn main() { let mut dst = [0, 0, 0]; let src = [1, 2, 3]; dst.copy_from_slice(&src); assert_eq!(src, dst); }
let mut dst = [0, 0, 0];
let src = [1, 2, 3];

dst.copy_from_slice(&src);
assert_eq!(src, dst);

fn pop(&mut self) -> Option<T>

Removes the last element from a vector and returns it, or None if it is empty.

Examples

fn main() { let mut vec = vec![1, 2, 3]; assert_eq!(vec.pop(), Some(3)); assert_eq!(vec, [1, 2]); }
let mut vec = vec![1, 2, 3];
assert_eq!(vec.pop(), Some(3));
assert_eq!(vec, [1, 2]);

fn remove(&mut self, index: usize) -> T

Removes and returns the element at position index within the vector, shifting all elements after it to the left.

Panics

Panics if index is out of bounds.

Examples

fn main() { let mut v = vec![1, 2, 3]; assert_eq!(v.remove(1), 2); assert_eq!(v, [1, 3]); }
let mut v = vec![1, 2, 3];
assert_eq!(v.remove(1), 2);
assert_eq!(v, [1, 3]);

fn swap_remove(&mut self, index: usize) -> T

Removes an element from anywhere in the vector and return it, replacing it with the last element.

This does not preserve ordering, but is O(1).

Panics

Panics if index is out of bounds.

Examples

fn main() { let mut v = vec!["foo", "bar", "baz", "qux"]; assert_eq!(v.swap_remove(1), "bar"); assert_eq!(v, ["foo", "qux", "baz"]); assert_eq!(v.swap_remove(0), "foo"); assert_eq!(v, ["baz", "qux"]); }
let mut v = vec!["foo", "bar", "baz", "qux"];

assert_eq!(v.swap_remove(1), "bar");
assert_eq!(v, ["foo", "qux", "baz"]);

assert_eq!(v.swap_remove(0), "foo");
assert_eq!(v, ["baz", "qux"]);

fn truncate(&mut self, len: usize)

Shorten a vector to be len elements long, dropping excess elements.

If len is greater than the vector's current length, this has no effect.

Examples

fn main() { let mut vec = vec![1, 2, 3, 4, 5]; vec.truncate(2); assert_eq!(vec, [1, 2]); }
let mut vec = vec![1, 2, 3, 4, 5];
vec.truncate(2);
assert_eq!(vec, [1, 2]);

fn drain<R>(&mut self, range: R) -> Drain<T> where R: RangeArgument<usize>
1.6.0

Create a draining iterator that removes the specified range in the vector and yields the removed items.

Note 1: The element range is removed even if the iterator is not consumed until the end.

Note 2: It is unspecified how many elements are removed from the vector, if the Drain value is leaked.

Panics

Panics if the starting point is greater than the end point or if the end point is greater than the length of the vector.

Examples

fn main() { let mut v = vec![1, 2, 3]; let u: Vec<_> = v.drain(1..).collect(); assert_eq!(v, &[1]); assert_eq!(u, &[2, 3]); // A full range clears the vector v.drain(..); assert_eq!(v, &[]); }
let mut v = vec![1, 2, 3];
let u: Vec<_> = v.drain(1..).collect();
assert_eq!(v, &[1]);
assert_eq!(u, &[2, 3]);

// A full range clears the vector
v.drain(..);
assert_eq!(v, &[]);

fn clear(&mut self)

Clears the vector, removing all values.

Examples

fn main() { let mut v = vec![1, 2, 3]; v.clear(); assert!(v.is_empty()); }
let mut v = vec![1, 2, 3];

v.clear();

assert!(v.is_empty());

fn retain<F>(&mut self, f: F) where F: FnMut(&T) -> bool

Retains only the elements specified by the predicate.

In other words, remove all elements e such that f(&e) returns false. This method operates in place and preserves the order of the retained elements.

Examples

fn main() { let mut vec = vec![1, 2, 3, 4]; vec.retain(|&x| x%2 == 0); assert_eq!(vec, [2, 4]); }
let mut vec = vec![1, 2, 3, 4];
vec.retain(|&x| x%2 == 0);
assert_eq!(vec, [2, 4]);

fn dedup(&mut self)

Removes consecutive repeated elements in the vector.

If the vector is sorted, this removes all duplicates.

Examples

fn main() { let mut vec = vec![1, 2, 2, 3, 2]; vec.dedup(); assert_eq!(vec, [1, 2, 3, 2]); }
let mut vec = vec![1, 2, 2, 3, 2];

vec.dedup();

assert_eq!(vec, [1, 2, 3, 2]);

fn sort(&mut self) where T: Ord

This is equivalent to self.sort_by(|a, b| a.cmp(b)).

This sort is stable and O(n log n) worst-case but allocates approximately 2 * n where n is the length of self.

Examples

fn main() { let mut v = [-5, 4, 1, -3, 2]; v.sort(); assert!(v == [-5, -3, 1, 2, 4]); }
let mut v = [-5, 4, 1, -3, 2];

v.sort();
assert!(v == [-5, -3, 1, 2, 4]);

fn sort_by<F>(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering

Sorts the slice, in place, using compare to compare elements.

This sort is stable and O(n log n) worst-case but allocates approximately 2 * n, where n is the length of self.

Examples

fn main() { let mut v = [5, 4, 1, 3, 2]; v.sort_by(|a, b| a.cmp(b)); assert!(v == [1, 2, 3, 4, 5]); // reverse sorting v.sort_by(|a, b| b.cmp(a)); assert!(v == [5, 4, 3, 2, 1]); }
let mut v = [5, 4, 1, 3, 2];
v.sort_by(|a, b| a.cmp(b));
assert!(v == [1, 2, 3, 4, 5]);

// reverse sorting
v.sort_by(|a, b| b.cmp(a));
assert!(v == [5, 4, 3, 2, 1]);

fn sort_by_key<B, F>(&mut self, f: F) where B: Ord, F: FnMut(&T) -> B
1.7.0

Sorts the slice, in place, using key to extract a key by which to order the sort by.

This sort is stable and O(n log n) worst-case but allocates approximately 2 * n, where n is the length of self.

Examples

fn main() { let mut v = [-5i32, 4, 1, -3, 2]; v.sort_by_key(|k| k.abs()); assert!(v == [1, 2, -3, 4, -5]); }
let mut v = [-5i32, 4, 1, -3, 2];

v.sort_by_key(|k| k.abs());
assert!(v == [1, 2, -3, 4, -5]);

fn reverse(&mut self)

Reverse the order of elements in a slice, in place.

Example

fn main() { let mut v = [1, 2, 3]; v.reverse(); assert!(v == [3, 2, 1]); }
let mut v = [1, 2, 3];
v.reverse();
assert!(v == [3, 2, 1]);

fn swap(&mut self, a: usize, b: usize)

Swaps two elements in a slice.

Arguments

  • a - The index of the first element
  • b - The index of the second element

Panics

Panics if a or b are out of bounds.

Example

fn main() { let mut v = ["a", "b", "c", "d"]; v.swap(1, 3); assert!(v == ["a", "d", "c", "b"]); }
let mut v = ["a", "b", "c", "d"];
v.swap(1, 3);
assert!(v == ["a", "d", "c", "b"]);

fn iter(&self) -> Iter<T>

Returns an iterator over the slice.

fn iter_mut(&mut self) -> IterMut<T>

Returns an iterator that allows modifying each value

fn into_iter(self) -> IntoIter<T>

Creates a consuming iterator, that is, one that moves each value out of the vector (from start to end). The vector cannot be used after calling this.

Examples

fn main() { let v = vec!["a".to_string(), "b".to_string()]; for s in v.into_iter() { // s has type String, not &String println!("{}", s); } }
let v = vec!["a".to_string(), "b".to_string()];
for s in v.into_iter() {
    // s has type String, not &String
    println!("{}", s);
}

fn chunks(&self, size: usize) -> Chunks<T>

Returns an iterator over size elements of the slice at a time. The chunks are slices and do not overlap. If size does not divide the length of the slice, then the last chunk will not have length size.

Panics

Panics if size is 0.

Example

Print the slice two elements at a time (i.e. [1,2], [3,4], [5]):

fn main() { let v = &[1, 2, 3, 4, 5]; for chunk in v.chunks(2) { println!("{:?}", chunk); } }
let v = &[1, 2, 3, 4, 5];
for chunk in v.chunks(2) {
    println!("{:?}", chunk);
}

fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T>

Returns an iterator over chunk_size elements of the slice at a time. The chunks are mutable slices, and do not overlap. If chunk_size does not divide the length of the slice, then the last chunk will not have length chunk_size.

Panics

Panics if chunk_size is 0.

fn windows(&self, size: usize) -> Windows<T>

Returns an iterator over all contiguous windows of length size. The windows overlap. If the slice is shorter than size, the iterator returns no values.

Panics

Panics if size is 0.

Example

Print the adjacent pairs of a slice (i.e. [1,2], [2,3], [3,4]):

fn main() { let v = &[1, 2, 3, 4]; for win in v.windows(2) { println!("{:?}", win); } }
let v = &[1, 2, 3, 4];
for win in v.windows(2) {
    println!("{:?}", win);
}

fn into_boxed_slice(self) -> Box<[T]>

Converts the vector into Box<[T]>.

Note that this will drop any excess capacity. Calling this and converting back to a vector with into_vec() is equivalent to calling shrink_to_fit().

fn as_ref(&self) -> &Vec<T>

Performs the conversion.

fn to_vec(&self) -> Vec<T> where T: Clone

Copies self into a new Vec.

fn as_slice(&self) -> &[T]
1.7.0

Extracts a slice containing the entire vector.

Equivalent to &s[..].

fn as_mut_slice(&mut self) -> &mut [T]
1.7.0

Extracts a mutable slice of the entire vector.

Equivalent to &mut s[..].

fn capacity(&self) -> usize

Returns the number of elements the vector can hold without reallocating.

Examples

fn main() { let vec: Vec<i32> = Vec::with_capacity(10); assert_eq!(vec.capacity(), 10); }
let vec: Vec<i32> = Vec::with_capacity(10);
assert_eq!(vec.capacity(), 10);

fn reserve(&mut self, additional: usize)

Reserves capacity for at least additional more elements to be inserted in the given Vec<T>. The collection may reserve more space to avoid frequent reallocations.

Panics

Panics if the new capacity overflows usize.

Examples

fn main() { let mut vec = vec![1]; vec.reserve(10); assert!(vec.capacity() >= 11); }
let mut vec = vec![1];
vec.reserve(10);
assert!(vec.capacity() >= 11);

fn reserve_exact(&mut self, additional: usize)

Reserves the minimum capacity for exactly additional more elements to be inserted in the given Vec<T>. 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 if future insertions are expected.

Panics

Panics if the new capacity overflows usize.

Examples

fn main() { let mut vec = vec![1]; vec.reserve_exact(10); assert!(vec.capacity() >= 11); }
let mut vec = vec![1];
vec.reserve_exact(10);
assert!(vec.capacity() >= 11);

fn shrink_to_fit(&mut self)

Shrinks the capacity of the vector as much as possible.

It will drop down as close as possible to the length but the allocator may still inform the vector that there is space for a few more elements.

Examples

fn main() { let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3].iter().cloned()); assert_eq!(vec.capacity(), 10); vec.shrink_to_fit(); assert!(vec.capacity() >= 3); }
let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3].iter().cloned());
assert_eq!(vec.capacity(), 10);
vec.shrink_to_fit();
assert!(vec.capacity() >= 3);

fn split_at(&self, mid: usize) -> (&[T], &[T])

Divides one slice into two at an index.

The first will contain all indices from [0, mid) (excluding the index mid itself) and the second will contain all indices from [mid, len) (excluding the index len itself).

Panics

Panics if mid > len.

Examples

fn main() { let v = [10, 40, 30, 20, 50]; let (v1, v2) = v.split_at(2); assert_eq!([10, 40], v1); assert_eq!([30, 20, 50], v2); }
let v = [10, 40, 30, 20, 50];
let (v1, v2) = v.split_at(2);
assert_eq!([10, 40], v1);
assert_eq!([30, 20, 50], v2);

fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])

Divides one &mut into two at an index.

The first will contain all indices from [0, mid) (excluding the index mid itself) and the second will contain all indices from [mid, len) (excluding the index len itself).

Panics

Panics if mid > len.

Example

fn main() { let mut v = [1, 2, 3, 4, 5, 6]; // scoped to restrict the lifetime of the borrows { let (left, right) = v.split_at_mut(0); assert!(left == []); assert!(right == [1, 2, 3, 4, 5, 6]); } { let (left, right) = v.split_at_mut(2); assert!(left == [1, 2]); assert!(right == [3, 4, 5, 6]); } { let (left, right) = v.split_at_mut(6); assert!(left == [1, 2, 3, 4, 5, 6]); assert!(right == []); } }
let mut v = [1, 2, 3, 4, 5, 6];

// scoped to restrict the lifetime of the borrows
{
   let (left, right) = v.split_at_mut(0);
   assert!(left == []);
   assert!(right == [1, 2, 3, 4, 5, 6]);
}

{
    let (left, right) = v.split_at_mut(2);
    assert!(left == [1, 2]);
    assert!(right == [3, 4, 5, 6]);
}

{
    let (left, right) = v.split_at_mut(6);
    assert!(left == [1, 2, 3, 4, 5, 6]);
    assert!(right == []);
}

fn split<F>(&self, pred: F) -> Split<T, F> where F: FnMut(&T) -> bool

Returns an iterator over subslices separated by elements that match pred. The matched element is not contained in the subslices.

Examples

Print the slice split by numbers divisible by 3 (i.e. [10, 40], [20], [50]):

fn main() { let v = [10, 40, 30, 20, 60, 50]; for group in v.split(|num| *num % 3 == 0) { println!("{:?}", group); } }
let v = [10, 40, 30, 20, 60, 50];
for group in v.split(|num| *num % 3 == 0) {
    println!("{:?}", group);
}

fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F> where F: FnMut(&T) -> bool

Returns an iterator over mutable subslices separated by elements that match pred. The matched element is not contained in the subslices.

fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F> where F: FnMut(&T) -> bool

Returns an iterator over subslices separated by elements that match pred, limited to returning at most n items. The matched element is not contained in the subslices.

The last element returned, if any, will contain the remainder of the slice.

Examples

Print the slice split once by numbers divisible by 3 (i.e. [10, 40], [20, 60, 50]):

fn main() { let v = [10, 40, 30, 20, 60, 50]; for group in v.splitn(2, |num| *num % 3 == 0) { println!("{:?}", group); } }
let v = [10, 40, 30, 20, 60, 50];
for group in v.splitn(2, |num| *num % 3 == 0) {
    println!("{:?}", group);
}

fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F> where F: FnMut(&T) -> bool

Returns an iterator over subslices separated by elements that match pred, limited to returning at most n items. The matched element is not contained in the subslices.

The last element returned, if any, will contain the remainder of the slice.

fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F> where F: FnMut(&T) -> bool

Returns an iterator over subslices separated by elements that match pred limited to returning at most n items. This starts at the end of the slice and works backwards. The matched element is not contained in the subslices.

The last element returned, if any, will contain the remainder of the slice.

Examples

Print the slice split once, starting from the end, by numbers divisible by 3 (i.e. [50], [10, 40, 30, 20]):

fn main() { let v = [10, 40, 30, 20, 60, 50]; for group in v.rsplitn(2, |num| *num % 3 == 0) { println!("{:?}", group); } }
let v = [10, 40, 30, 20, 60, 50];
for group in v.rsplitn(2, |num| *num % 3 == 0) {
    println!("{:?}", group);
}

fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F> where F: FnMut(&T) -> bool

Returns an iterator over subslices separated by elements that match pred limited to returning at most n items. This starts at the end of the slice and works backwards. The matched element is not contained in the subslices.

The last element returned, if any, will contain the remainder of the slice.

fn split_off(&mut self, at: usize) -> Vec<T>
1.4.0

Splits the collection into two at the given index.

Returns a newly allocated Self. self contains elements [0, at), and the returned Self contains elements [at, len).

Note that the capacity of self does not change.

Panics

Panics if at > len.

Examples

fn main() { let mut vec = vec![1,2,3]; let vec2 = vec.split_off(1); assert_eq!(vec, [1]); assert_eq!(vec2, [2, 3]); }
let mut vec = vec![1,2,3];
let vec2 = vec.split_off(1);
assert_eq!(vec, [1]);
assert_eq!(vec2, [2, 3]);

fn cmp(&self, other: &Vec<T>) -> Ordering

This method returns an Ordering between self and other. Read more

fn eq(&self, other: &Vec<B>) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &Vec<B>) -> bool

This method tests for !=.

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more

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

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more

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

fn hash<H>(&self, state: &mut H) where H: Hasher

Feeds this value into the state given, updating the hasher as necessary.

impl<T> From<BinaryHeap<T>> for Vec<T>

fn from(heap: BinaryHeap<T>) -> Vec<T>

Performs the conversion.

impl<T> Borrow<[T]> for Vec<T>

fn borrow(&self) -> &[T]

Immutably borrows from an owned value. Read more

impl<T> BorrowMut<[T]> for Vec<T>

fn borrow_mut(&mut self) -> &mut [T]

Mutably borrows from an owned value. Read more

impl<T> Clone for Vec<T> where T: Clone

fn clone(&self) -> Vec<T>

Returns a copy of the value. Read more

fn clone_from(&mut self, other: &Vec<T>)

Performs copy-assignment from source. Read more

impl<T> Hash for Vec<T> where T: Hash

fn hash<H>(&self, state: &mut H) where H: Hasher

Feeds this value into the state given, updating the hasher as necessary.

fn hash_slice<H>(data: &[Self], state: &mut H) where H: Hasher
1.3.0

Feeds a slice of this type into the state provided.

impl<T> Index<usize> for Vec<T>

type Output = T

The returned type after indexing

fn index(&self, index: usize) -> &T

The method for the indexing (Foo[Bar]) operation

impl<T> IndexMut<usize> for Vec<T>

fn index_mut(&mut self, index: usize) -> &mut T

The method for the indexing (Foo[Bar]) operation

impl<T> Index<Range<usize>> for Vec<T>

type Output = [T]

The returned type after indexing

fn index(&self, index: Range<usize>) -> &[T]

The method for the indexing (Foo[Bar]) operation

impl<T> Index<RangeTo<usize>> for Vec<T>

type Output = [T]

The returned type after indexing

fn index(&self, index: RangeTo<usize>) -> &[T]

The method for the indexing (Foo[Bar]) operation

impl<T> Index<RangeFrom<usize>> for Vec<T>

type Output = [T]

The returned type after indexing

fn index(&self, index: RangeFrom<usize>) -> &[T]

The method for the indexing (Foo[Bar]) operation

impl<T> Index<RangeFull> for Vec<T>

type Output = [T]

The returned type after indexing

fn index(&self, _index: RangeFull) -> &[T]

The method for the indexing (Foo[Bar]) operation

impl<T> Index<RangeInclusive<usize>> for Vec<T>

type Output = [T]

The returned type after indexing

fn index(&self, index: RangeInclusive<usize>) -> &[T]

The method for the indexing (Foo[Bar]) operation

impl<T> Index<RangeToInclusive<usize>> for Vec<T>

type Output = [T]

The returned type after indexing

fn index(&self, index: RangeToInclusive<usize>) -> &[T]

The method for the indexing (Foo[Bar]) operation

impl<T> IndexMut<Range<usize>> for Vec<T>

fn index_mut(&mut self, index: Range<usize>) -> &mut [T]

The method for the indexing (Foo[Bar]) operation

impl<T> IndexMut<RangeTo<usize>> for Vec<T>

fn index_mut(&mut self, index: RangeTo<usize>) -> &mut [T]

The method for the indexing (Foo[Bar]) operation

impl<T> IndexMut<RangeFrom<usize>> for Vec<T>

fn index_mut(&mut self, index: RangeFrom<usize>) -> &mut [T]

The method for the indexing (Foo[Bar]) operation

impl<T> IndexMut<RangeFull> for Vec<T>

fn index_mut(&mut self, _index: RangeFull) -> &mut [T]

The method for the indexing (Foo[Bar]) operation

impl<T> IndexMut<RangeInclusive<usize>> for Vec<T>

fn index_mut(&mut self, index: RangeInclusive<usize>) -> &mut [T]

The method for the indexing (Foo[Bar]) operation

impl<T> IndexMut<RangeToInclusive<usize>> for Vec<T>

fn index_mut(&mut self, index: RangeToInclusive<usize>) -> &mut [T]

The method for the indexing (Foo[Bar]) operation

impl<T> Deref for Vec<T>

type Target = [T]

The resulting type after dereferencing

fn deref(&self) -> &[T]

The method called to dereference a value

impl<T> DerefMut for Vec<T>

fn deref_mut(&mut self) -> &mut [T]

The method called to mutably dereference a value

impl<T> FromIterator<T> for Vec<T>

fn from_iter<I>(iter: I) -> Vec<T> where I: IntoIterator<Item=T>

Creates a value from an iterator. Read more

impl<T> IntoIterator for Vec<T>

type Item = T

The type of the elements being iterated over.

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?

fn into_iter(self) -> IntoIter<T>

Creates a consuming iterator, that is, one that moves each value out of the vector (from start to end). The vector cannot be used after calling this.

Examples

fn main() { let v = vec!["a".to_string(), "b".to_string()]; for s in v.into_iter() { // s has type String, not &String println!("{}", s); } }
let v = vec!["a".to_string(), "b".to_string()];
for s in v.into_iter() {
    // s has type String, not &String
    println!("{}", s);
}

impl<'a, T> IntoIterator for &'a Vec<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?

fn into_iter(self) -> Iter<'a, T>

Creates an iterator from a value. Read more

impl<'a, T> IntoIterator for &'a mut Vec<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?

fn into_iter(self) -> IterMut<'a, T>

Creates an iterator from a value. Read more

impl<T> Extend<T> for Vec<T>

fn extend<I>(&mut self, iter: I) where I: IntoIterator<Item=T>

Extends a collection with the contents of an iterator. Read more

impl<'a, T> Extend<&'a T> for Vec<T> where T: Copy + 'a
1.2.0

fn extend<I>(&mut self, iter: I) where I: IntoIterator<Item=&'a T>

Extends a collection with the contents of an iterator. Read more

impl<'a, 'b, A, B> PartialEq<Vec<B>> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &Vec<B>) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &Vec<B>) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b mut [B]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b mut [B]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b mut [B]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 0]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 0]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 0]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 0]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 0]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 0]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 1]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 1]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 1]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 1]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 1]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 1]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 2]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 2]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 2]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 2]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 2]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 2]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 3]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 3]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 3]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 3]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 3]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 3]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 4]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 4]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 4]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 4]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 4]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 4]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 5]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 5]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 5]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 5]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 5]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 5]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 6]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 6]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 6]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 6]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 6]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 6]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 7]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 7]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 7]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 7]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 7]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 7]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 8]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 8]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 8]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 8]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 8]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 8]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 9]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 9]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 9]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 9]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 9]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 9]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 10]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 10]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 10]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 10]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 10]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 10]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 11]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 11]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 11]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 11]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 11]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 11]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 12]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 12]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 12]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 12]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 12]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 12]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 13]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 13]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 13]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 13]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 13]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 13]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 14]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 14]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 14]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 14]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 14]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 14]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 15]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 15]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 15]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 15]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 15]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 15]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 16]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 16]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 16]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 16]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 16]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 16]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 17]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 17]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 17]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 17]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 17]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 17]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 18]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 18]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 18]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 18]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 18]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 18]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 19]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 19]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 19]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 19]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 19]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 19]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 20]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 20]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 20]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 20]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 20]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 20]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 21]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 21]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 21]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 21]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 21]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 21]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 22]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 22]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 22]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 22]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 22]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 22]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 23]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 23]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 23]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 23]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 23]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 23]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 24]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 24]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 24]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 24]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 24]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 24]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 25]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 25]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 25]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 25]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 25]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 25]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 26]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 26]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 26]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 26]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 26]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 26]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 27]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 27]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 27]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 27]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 27]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 27]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 28]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 28]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 28]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 28]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 28]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 28]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 29]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 29]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 29]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 29]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 29]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 29]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 30]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 30]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 30]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 30]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 30]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 30]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 31]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 31]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 31]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 31]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 31]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 31]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<[B; 32]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &[B; 32]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &[B; 32]) -> bool

This method tests for !=.

impl<'a, 'b, A, B> PartialEq<&'b [B; 32]> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &&'b [B; 32]) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &&'b [B; 32]) -> bool

This method tests for !=.

impl<T> PartialOrd<Vec<T>> for Vec<T> where T: PartialOrd<T>

fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more

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

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more

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

impl<T> Eq for Vec<T> where T: Eq

impl<T> Ord for Vec<T> where T: Ord

fn cmp(&self, other: &Vec<T>) -> Ordering

This method returns an Ordering between self and other. Read more

impl<T> Drop for Vec<T>

fn drop(&mut self)

A method called when the value goes out of scope. Read more

impl<T> Default for Vec<T>

fn default() -> Vec<T>

Returns the "default value" for a type. Read more

impl<T> Debug for Vec<T> where T: Debug

fn fmt(&self, f: &mut Formatter) -> Result<()Error>

Formats the value using the given formatter.

impl<T> AsRef<Vec<T>> for Vec<T>

fn as_ref(&self) -> &Vec<T>

Performs the conversion.

impl<T> AsMut<Vec<T>> for Vec<T>
1.5.0

fn as_mut(&mut self) -> &mut Vec<T>

Performs the conversion.

impl<T> AsRef<[T]> for Vec<T>

fn as_ref(&self) -> &[T]

Performs the conversion.

impl<T> AsMut<[T]> for Vec<T>
1.5.0

fn as_mut(&mut self) -> &mut [T]

Performs the conversion.

impl<'a, T> From<&'a [T]> for Vec<T> where T: Clone

fn from(s: &'a [T]) -> Vec<T>

Performs the conversion.

impl<'a> From<&'a str> for Vec<u8>

fn from(s: &'a str) -> Vec<u8>

Performs the conversion.

impl<T> From<VecDeque<T>> for Vec<T>
1.10.0

fn from(other: VecDeque<T>) -> Vec<T>

Performs the conversion.

impl From<CString> for Vec<u8>
1.7.0
[src]

fn from(s: CString) -> Vec<u8>

Performs the conversion.

impl Write for Vec<u8>
[src]

fn write(&mut self, buf: &[u8]) -> Result<usize>

Write a buffer into this object, returning how many bytes were written. Read more

fn write_all(&mut self, buf: &[u8]) -> Result<()>

Attempts to write an entire buffer into this write. Read more

fn flush(&mut self) -> Result<()>

Flush this output stream, ensuring that all intermediately buffered contents reach their destination. Read more

fn write_fmt(&mut self, fmt: Arguments) -> Result<()>

Writes a formatted string into this writer, returning any error encountered. Read more

fn by_ref(&mut self) -> &mut Self where Self: Sized

Creates a "by reference" adaptor for this instance of Write. Read more

impl<'a, 'b, A, B> PartialEq<Vec<B>> for Vec<A> where A: PartialEq<B>

fn eq(&self, other: &Vec<B>) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &Vec<B>) -> bool

This method tests for !=.

impl<T> PartialOrd<Vec<T>> for Vec<T> where T: PartialOrd<T>

fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more

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

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more

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

impl<T> Ord for Vec<T> where T: Ord

fn cmp(&self, other: &Vec<T>) -> Ordering

This method returns an Ordering between self and other. Read more

impl<T> Drop for Vec<T>

fn drop(&mut self)

A method called when the value goes out of scope. Read more

impl<T> Default for Vec<T>

fn default() -> Vec<T>

Returns the "default value" for a type. Read more

impl<T> Debug for Vec<T> where T: Debug

fn fmt(&self, f: &mut Formatter) -> Result<()Error>

Formats the value using the given formatter.

impl<T> AsRef<Vec<T>> for Vec<T>

fn as_ref(&self) -> &Vec<T>

Performs the conversion.

impl<T> AsMut<Vec<T>> for Vec<T>
1.5.0

fn as_mut(&mut self) -> &mut Vec<T>

Performs the conversion.

impl<T> AsRef<[T]> for Vec<T>

fn as_ref(&self) -> &[T]

Performs the conversion.

impl<T> AsMut<[T]> for Vec<T>
1.5.0

fn as_mut(&mut self) -> &mut [T]

Performs the conversion.

impl<'a, T> From<&'a [T]> for Vec<T> where T: Clone

fn from(s: &'a [T]) -> Vec<T>

Performs the conversion.

impl<'a> From<&'a str> for Vec<u8>

fn from(s: &'a str) -> Vec<u8>

Performs the conversion.

impl<T> From<VecDeque<T>> for Vec<T>
1.10.0

fn from(other: VecDeque<T>) -> Vec<T>

Performs the conversion.

impl From<CString> for Vec<u8>
1.7.0
[src]

fn from(s: CString) -> Vec<u8>

Performs the conversion.

impl Write for Vec<u8>
[src]

fn write(&mut self, buf: &[u8]) -> Result<usize>

Write a buffer into this object, returning how many bytes were written. Read more

fn write_all(&mut self, buf: &[u8]) -> Result<()>

Attempts to write an entire buffer into this write. Read more

fn flush(&mut self) -> Result<()>

Flush this output stream, ensuring that all intermediately buffered contents reach their destination. Read more

fn write_fmt(&mut self, fmt: Arguments) -> Result<()>

Writes a formatted string into this writer, returning any error encountered. Read more

fn by_ref(&mut self) -> &mut Self where Self: Sized

Creates a "by reference" adaptor for this instance of Write. Read more

std::vec! []

macro_rules! vec {
    ( $ elem : expr ; $ n : expr ) => { ... };
    ( $ ( $ x : expr ) , * ) => { ... };
    ( $ ( $ x : expr , ) * ) => { ... };
}

Creates a Vec containing the arguments.

vec! allows Vecs to be defined with the same syntax as array expressions. There are two forms of this macro:

  • Create a Vec containing a given list of elements:
fn main() { let v = vec![1, 2, 3]; assert_eq!(v[0], 1); assert_eq!(v[1], 2); assert_eq!(v[2], 3); }
let v = vec![1, 2, 3];
assert_eq!(v[0], 1);
assert_eq!(v[1], 2);
assert_eq!(v[2], 3);
  • Create a Vec from a given element and size:
fn main() { let v = vec![1; 3]; assert_eq!(v, [1, 1, 1]); }
let v = vec![1; 3];
assert_eq!(v, [1, 1, 1]);

Note that unlike array expressions this syntax supports all elements which implement Clone and the number of elements doesn't have to be a constant.

This will use clone() to duplicate an expression, so one should be careful using this with types having a nonstandard Clone implementation. For example, vec![Rc::new(1); 5] will create a vector of five references to the same boxed integer value, not five references pointing to independently boxed integers.

Trait std::iter::IntoIterator1.0.0 [] [src]

pub trait IntoIterator where Self::IntoIter::Item == Self::Item {
    type Item;
    type IntoIter: Iterator;
    fn into_iter(self) -> Self::IntoIter;
}

Conversion into an Iterator.

By implementing IntoIterator for a type, you define how it will be converted to an iterator. This is common for types which describe a collection of some kind.

One benefit of implementing IntoIterator is that your type will work with Rust's for loop syntax.

See also: FromIterator.

Examples

Basic usage:

fn main() { let v = vec![1, 2, 3]; let mut iter = v.into_iter(); let n = iter.next(); assert_eq!(Some(1), n); let n = iter.next(); assert_eq!(Some(2), n); let n = iter.next(); assert_eq!(Some(3), n); let n = iter.next(); assert_eq!(None, n); }
let v = vec![1, 2, 3];

let mut iter = v.into_iter();

let n = iter.next();
assert_eq!(Some(1), n);

let n = iter.next();
assert_eq!(Some(2), n);

let n = iter.next();
assert_eq!(Some(3), n);

let n = iter.next();
assert_eq!(None, n);

Implementing IntoIterator for your type:

fn main() { // A sample collection, that's just a wrapper over Vec<T> #[derive(Debug)] struct MyCollection(Vec<i32>); // Let's give it some methods so we can create one and add things // to it. impl MyCollection { fn new() -> MyCollection { MyCollection(Vec::new()) } fn add(&mut self, elem: i32) { self.0.push(elem); } } // and we'll implement IntoIterator impl IntoIterator for MyCollection { type Item = i32; type IntoIter = ::std::vec::IntoIter<i32>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } // Now we can make a new collection... let mut c = MyCollection::new(); // ... add some stuff to it ... c.add(0); c.add(1); c.add(2); // ... and then turn it into an Iterator: for (i, n) in c.into_iter().enumerate() { assert_eq!(i as i32, n); } }
// A sample collection, that's just a wrapper over Vec<T>
#[derive(Debug)]
struct MyCollection(Vec<i32>);

// Let's give it some methods so we can create one and add things
// to it.
impl MyCollection {
    fn new() -> MyCollection {
        MyCollection(Vec::new())
    }

    fn add(&mut self, elem: i32) {
        self.0.push(elem);
    }
}

// and we'll implement IntoIterator
impl IntoIterator for MyCollection {
    type Item = i32;
    type IntoIter = ::std::vec::IntoIter<i32>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

// Now we can make a new collection...
let mut c = MyCollection::new();

// ... add some stuff to it ...
c.add(0);
c.add(1);
c.add(2);

// ... and then turn it into an Iterator:
for (i, n) in c.into_iter().enumerate() {
    assert_eq!(i as i32, n);
}

Associated Types

type Item

The type of the elements being iterated over.

type IntoIter: Iterator

Which kind of iterator are we turning this into?

Required Methods

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value.

See the module-level documentation for more.

Examples

Basic usage:

fn main() { let v = vec![1, 2, 3]; let mut iter = v.into_iter(); let n = iter.next(); assert_eq!(Some(1), n); let n = iter.next(); assert_eq!(Some(2), n); let n = iter.next(); assert_eq!(Some(3), n); let n = iter.next(); assert_eq!(None, n); }
let v = vec![1, 2, 3];

let mut iter = v.into_iter();

let n = iter.next();
assert_eq!(Some(1), n);

let n = iter.next();
assert_eq!(Some(2), n);

let n = iter.next();
assert_eq!(Some(3), n);

let n = iter.next();
assert_eq!(None, n);

Implementors

  • impl<'a, T> IntoIterator for &'a [T; 0]
  • impl<'a, T> IntoIterator for &'a mut [T; 0]
  • impl<'a, T> IntoIterator for &'a [T; 1]
  • impl<'a, T> IntoIterator for &'a mut [T; 1]
  • impl<'a, T> IntoIterator for &'a [T; 2]
  • impl<'a, T> IntoIterator for &'a mut [T; 2]
  • impl<'a, T> IntoIterator for &'a [T; 3]
  • impl<'a, T> IntoIterator for &'a mut [T; 3]
  • impl<'a, T> IntoIterator for &'a [T; 4]
  • impl<'a, T> IntoIterator for &'a mut [T; 4]
  • impl<'a, T> IntoIterator for &'a [T; 5]
  • impl<'a, T> IntoIterator for &'a mut [T; 5]
  • impl<'a, T> IntoIterator for &'a [T; 6]
  • impl<'a, T> IntoIterator for &'a mut [T; 6]
  • impl<'a, T> IntoIterator for &'a [T; 7]
  • impl<'a, T> IntoIterator for &'a mut [T; 7]
  • impl<'a, T> IntoIterator for &'a [T; 8]
  • impl<'a, T> IntoIterator for &'a mut [T; 8]
  • impl<'a, T> IntoIterator for &'a [T; 9]
  • impl<'a, T> IntoIterator for &'a mut [T; 9]
  • impl<'a, T> IntoIterator for &'a [T; 10]
  • impl<'a, T> IntoIterator for &'a mut [T; 10]
  • impl<'a, T> IntoIterator for &'a [T; 11]
  • impl<'a, T> IntoIterator for &'a mut [T; 11]
  • impl<'a, T> IntoIterator for &'a [T; 12]
  • impl<'a, T> IntoIterator for &'a mut [T; 12]
  • impl<'a, T> IntoIterator for &'a [T; 13]
  • impl<'a, T> IntoIterator for &'a mut [T; 13]
  • impl<'a, T> IntoIterator for &'a [T; 14]
  • impl<'a, T> IntoIterator for &'a mut [T; 14]
  • impl<'a, T> IntoIterator for &'a [T; 15]
  • impl<'a, T> IntoIterator for &'a mut [T; 15]
  • impl<'a, T> IntoIterator for &'a [T; 16]
  • impl<'a, T> IntoIterator for &'a mut [T; 16]
  • impl<'a, T> IntoIterator for &'a [T; 17]
  • impl<'a, T> IntoIterator for &'a mut [T; 17]
  • impl<'a, T> IntoIterator for &'a [T; 18]
  • impl<'a, T> IntoIterator for &'a mut [T; 18]
  • impl<'a, T> IntoIterator for &'a [T; 19]
  • impl<'a, T> IntoIterator for &'a mut [T; 19]
  • impl<'a, T> IntoIterator for &'a [T; 20]
  • impl<'a, T> IntoIterator for &'a mut [T; 20]
  • impl<'a, T> IntoIterator for &'a [T; 21]
  • impl<'a, T> IntoIterator for &'a mut [T; 21]
  • impl<'a, T> IntoIterator for &'a [T; 22]
  • impl<'a, T> IntoIterator for &'a mut [T; 22]
  • impl<'a, T> IntoIterator for &'a [T; 23]
  • impl<'a, T> IntoIterator for &'a mut [T; 23]
  • impl<'a, T> IntoIterator for &'a [T; 24]
  • impl<'a, T> IntoIterator for &'a mut [T; 24]
  • impl<'a, T> IntoIterator for &'a [T; 25]
  • impl<'a, T> IntoIterator for &'a mut [T; 25]
  • impl<'a, T> IntoIterator for &'a [T; 26]
  • impl<'a, T> IntoIterator for &'a mut [T; 26]
  • impl<'a, T> IntoIterator for &'a [T; 27]
  • impl<'a, T> IntoIterator for &'a mut [T; 27]
  • impl<'a, T> IntoIterator for &'a [T; 28]
  • impl<'a, T> IntoIterator for &'a mut [T; 28]
  • impl<'a, T> IntoIterator for &'a [T; 29]
  • impl<'a, T> IntoIterator for &'a mut [T; 29]
  • impl<'a, T> IntoIterator for &'a [T; 30]
  • impl<'a, T> IntoIterator for &'a mut [T; 30]
  • impl<'a, T> IntoIterator for &'a [T; 31]
  • impl<'a, T> IntoIterator for &'a mut [T; 31]
  • impl<'a, T> IntoIterator for &'a [T; 32]
  • impl<'a, T> IntoIterator for &'a mut [T; 32]
  • impl<I> IntoIterator for I where I: Iterator
  • impl<T> IntoIterator for Option<T>
  • impl<'a, T> IntoIterator for &'a Option<T>
  • impl<'a, T> IntoIterator for &'a mut Option<T>
  • impl<T, E> IntoIterator for Result<T, E>
  • impl<'a, T, E> IntoIterator for &'a Result<T, E>
  • impl<'a, T, E> IntoIterator for &'a mut Result<T, E>
  • impl<'a, T> IntoIterator for &'a [T]
  • impl<'a, T> IntoIterator for &'a mut [T]
  • impl<T> IntoIterator for BinaryHeap<T> where T: Ord
  • impl<'a, T> IntoIterator for &'a BinaryHeap<T> where T: Ord
  • impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V> where K: 'a, V: 'a
  • impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> where K: 'a, V: 'a
  • impl<K, V> IntoIterator for BTreeMap<K, V>
  • impl<T> IntoIterator for BTreeSet<T>
  • impl<'a, T> IntoIterator for &'a BTreeSet<T>
  • impl<'a, E> IntoIterator for &'a EnumSet<E> where E: CLike
  • impl<T> IntoIterator for LinkedList<T>
  • impl<'a, T> IntoIterator for &'a LinkedList<T>
  • impl<'a, T> IntoIterator for &'a mut LinkedList<T>
  • impl<T> IntoIterator for Vec<T>
  • impl<'a, T> IntoIterator for &'a Vec<T>
  • impl<'a, T> IntoIterator for &'a mut Vec<T>
  • impl<T> IntoIterator for VecDeque<T>
  • impl<'a, T> IntoIterator for &'a VecDeque<T>
  • impl<'a, T> IntoIterator for &'a mut VecDeque<T>
  • impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> where K: Eq + Hash, S: BuildHasher
  • impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> where K: Eq + Hash, S: BuildHasher
  • impl<K, V, S> IntoIterator for HashMap<K, V, S> where K: Eq + Hash, S: BuildHasher
  • impl<'a, T, S> IntoIterator for &'a HashSet<T, S> where T: Eq + Hash, S: BuildHasher
  • impl<T, S> IntoIterator for HashSet<T, S> where T: Eq + Hash, S: BuildHasher
  • impl<'a> IntoIterator for &'a UnixListener
  • impl<'a> IntoIterator for &'a PathBuf
  • impl<'a> IntoIterator for &'a Path
  • impl<'a, T> IntoIterator for &'a Receiver<T>
  • impl<T> IntoIterator for Receiver<T>

Trait std::iter::FromIterator1.0.0 [] [src]

pub trait FromIterator<A> {
    fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item=A>;
}

Conversion from an Iterator.

By implementing FromIterator for a type, you define how it will be created from an iterator. This is common for types which describe a collection of some kind.

FromIterator's from_iter() is rarely called explicitly, and is instead used through Iterator's collect() method. See collect()'s documentation for more examples.

See also: IntoIterator.

Examples

Basic usage:

fn main() { use std::iter::FromIterator; let five_fives = std::iter::repeat(5).take(5); let v = Vec::from_iter(five_fives); assert_eq!(v, vec![5, 5, 5, 5, 5]); }
use std::iter::FromIterator;

let five_fives = std::iter::repeat(5).take(5);

let v = Vec::from_iter(five_fives);

assert_eq!(v, vec![5, 5, 5, 5, 5]);

Using collect() to implicitly use FromIterator:

fn main() { let five_fives = std::iter::repeat(5).take(5); let v: Vec<i32> = five_fives.collect(); assert_eq!(v, vec![5, 5, 5, 5, 5]); }
let five_fives = std::iter::repeat(5).take(5);

let v: Vec<i32> = five_fives.collect();

assert_eq!(v, vec![5, 5, 5, 5, 5]);

Implementing FromIterator for your type:

fn main() { use std::iter::FromIterator; // A sample collection, that's just a wrapper over Vec<T> #[derive(Debug)] struct MyCollection(Vec<i32>); // Let's give it some methods so we can create one and add things // to it. impl MyCollection { fn new() -> MyCollection { MyCollection(Vec::new()) } fn add(&mut self, elem: i32) { self.0.push(elem); } } // and we'll implement FromIterator impl FromIterator<i32> for MyCollection { fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self { let mut c = MyCollection::new(); for i in iter { c.add(i); } c } } // Now we can make a new iterator... let iter = (0..5).into_iter(); // ... and make a MyCollection out of it let c = MyCollection::from_iter(iter); assert_eq!(c.0, vec![0, 1, 2, 3, 4]); // collect works too! let iter = (0..5).into_iter(); let c: MyCollection = iter.collect(); assert_eq!(c.0, vec![0, 1, 2, 3, 4]); }
use std::iter::FromIterator;

// A sample collection, that's just a wrapper over Vec<T>
#[derive(Debug)]
struct MyCollection(Vec<i32>);

// Let's give it some methods so we can create one and add things
// to it.
impl MyCollection {
    fn new() -> MyCollection {
        MyCollection(Vec::new())
    }

    fn add(&mut self, elem: i32) {
        self.0.push(elem);
    }
}

// and we'll implement FromIterator
impl FromIterator<i32> for MyCollection {
    fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
        let mut c = MyCollection::new();

        for i in iter {
            c.add(i);
        }

        c
    }
}

// Now we can make a new iterator...
let iter = (0..5).into_iter();

// ... and make a MyCollection out of it
let c = MyCollection::from_iter(iter);

assert_eq!(c.0, vec![0, 1, 2, 3, 4]);

// collect works too!

let iter = (0..5).into_iter();
let c: MyCollection = iter.collect();

assert_eq!(c.0, vec![0, 1, 2, 3, 4]);

Required Methods

fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item=A>

Creates a value from an iterator.

See the module-level documentation for more.

Examples

Basic usage:

fn main() { use std::iter::FromIterator; let five_fives = std::iter::repeat(5).take(5); let v = Vec::from_iter(five_fives); assert_eq!(v, vec![5, 5, 5, 5, 5]); }
use std::iter::FromIterator;

let five_fives = std::iter::repeat(5).take(5);

let v = Vec::from_iter(five_fives);

assert_eq!(v, vec![5, 5, 5, 5, 5]);

Implementors

Trait std::cmp::PartialEq1.0.0 [] [src]

pub trait PartialEq<Rhs = Self> where Rhs: ?Sized {
    fn eq(&self, other: &Rhs) -> bool;

    fn ne(&self, other: &Rhs) -> bool { ... }
}

Trait for equality comparisons which are partial equivalence relations.

This trait allows for partial equality, for types that do not have a full equivalence relation. For example, in floating point numbers NaN != NaN, so floating point types implement PartialEq but not Eq.

Formally, the equality must be (for all a, b and c):

  • symmetric: a == b implies b == a; and
  • transitive: a == b and b == c implies a == c.

Note that these requirements mean that the trait itself must be implemented symmetrically and transitively: if T: PartialEq<U> and U: PartialEq<V> then U: PartialEq<T> and T: PartialEq<V>.

Derivable

This trait can be used with #[derive]. When derived on structs, two instances are equal if all fields are equal, and not equal if any fields are not equal. When derived on enums, each variant is equal to itself and not equal to the other variants.

How can I implement PartialEq?

PartialEq only requires the eq method to be implemented; ne is defined in terms of it by default. Any manual implementation of ne must respect the rule that eq is a strict inverse of ne; that is, !(a == b) if and only if a != b.

An example implementation for a domain in which two books are considered the same book if their ISBN matches, even if the formats differ:

fn main() { enum BookFormat { Paperback, Hardback, Ebook } struct Book { isbn: i32, format: BookFormat, } impl PartialEq for Book { fn eq(&self, other: &Book) -> bool { self.isbn == other.isbn } } let b1 = Book { isbn: 3, format: BookFormat::Paperback }; let b2 = Book { isbn: 3, format: BookFormat::Ebook }; let b3 = Book { isbn: 10, format: BookFormat::Paperback }; assert!(b1 == b2); assert!(b1 != b3); }
enum BookFormat { Paperback, Hardback, Ebook }
struct Book {
    isbn: i32,
    format: BookFormat,
}

impl PartialEq for Book {
    fn eq(&self, other: &Book) -> bool {
        self.isbn == other.isbn
    }
}

let b1 = Book { isbn: 3, format: BookFormat::Paperback };
let b2 = Book { isbn: 3, format: BookFormat::Ebook };
let b3 = Book { isbn: 10, format: BookFormat::Paperback };

assert!(b1 == b2);
assert!(b1 != b3);

Examples

fn main() { let x: u32 = 0; let y: u32 = 1; assert_eq!(x == y, false); assert_eq!(x.eq(&y), false); }
let x: u32 = 0;
let y: u32 = 1;

assert_eq!(x == y, false);
assert_eq!(x.eq(&y), false);

Required Methods

fn eq(&self, other: &Rhs) -> bool

This method tests for self and other values to be equal, and is used by ==.

Provided Methods

fn ne(&self, other: &Rhs) -> bool

This method tests for !=.

Implementors

Trait std::cmp::PartialOrd1.0.0 [] [src]

pub trait PartialOrd<Rhs = Self>: PartialEq<Rhs> where Rhs: ?Sized {
    fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;

    fn lt(&self, other: &Rhs) -> bool { ... }
    fn le(&self, other: &Rhs) -> bool { ... }
    fn gt(&self, other: &Rhs) -> bool { ... }
    fn ge(&self, other: &Rhs) -> bool { ... }
}

Trait for values that can be compared for a sort-order.

The comparison must satisfy, for all a, b and c:

  • antisymmetry: if a < b then !(a > b), as well as a > b implying !(a < b); and
  • transitivity: a < b and b < c implies a < c. The same must hold for both == and >.

Note that these requirements mean that the trait itself must be implemented symmetrically and transitively: if T: PartialOrd<U> and U: PartialOrd<V> then U: PartialOrd<T> and T: PartialOrd<V>.

Derivable

This trait can be used with #[derive]. When derived, it will produce a lexicographic ordering based on the top-to-bottom declaration order of the struct's members.

How can I implement Ord?

PartialOrd only requires implementation of the partial_cmp method, with the others generated from default implementations.

However it remains possible to implement the others separately for types which do not have a total order. For example, for floating point numbers, NaN < 0 == false and NaN >= 0 == false (cf. IEEE 754-2008 section 5.11).

PartialOrd requires your type to be PartialEq.

If your type is Ord, you can implement partial_cmp() by using cmp():

fn main() { use std::cmp::Ordering; #[derive(Eq)] struct Person { id: u32, name: String, height: u32, } impl PartialOrd for Person { fn partial_cmp(&self, other: &Person) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for Person { fn cmp(&self, other: &Person) -> Ordering { self.height.cmp(&other.height) } } impl PartialEq for Person { fn eq(&self, other: &Person) -> bool { self.height == other.height } } }
use std::cmp::Ordering;

#[derive(Eq)]
struct Person {
    id: u32,
    name: String,
    height: u32,
}

impl PartialOrd for Person {
    fn partial_cmp(&self, other: &Person) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Person {
    fn cmp(&self, other: &Person) -> Ordering {
        self.height.cmp(&other.height)
    }
}

impl PartialEq for Person {
    fn eq(&self, other: &Person) -> bool {
        self.height == other.height
    }
}

You may also find it useful to use partial_cmp() on your types fields. Here is an example ofPersontypes who have a floating-pointheight` field that is the only field to be used for sorting:

fn main() { use std::cmp::Ordering; struct Person { id: u32, name: String, height: f64, } impl PartialOrd for Person { fn partial_cmp(&self, other: &Person) -> Option<Ordering> { self.height.partial_cmp(&other.height) } } impl PartialEq for Person { fn eq(&self, other: &Person) -> bool { self.height == other.height } } }
use std::cmp::Ordering;

struct Person {
    id: u32,
    name: String,
    height: f64,
}

impl PartialOrd for Person {
    fn partial_cmp(&self, other: &Person) -> Option<Ordering> {
        self.height.partial_cmp(&other.height)
    }
}

impl PartialEq for Person {
    fn eq(&self, other: &Person) -> bool {
        self.height == other.height
    }
}

Examples

fn main() { let x : u32 = 0; let y : u32 = 1; assert_eq!(x < y, true); assert_eq!(x.lt(&y), true); }
let x : u32 = 0;
let y : u32 = 1;

assert_eq!(x < y, true);
assert_eq!(x.lt(&y), true);

Required Methods

fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>

This method returns an ordering between self and other values if one exists.

Examples

fn main() { use std::cmp::Ordering; let result = 1.0.partial_cmp(&2.0); assert_eq!(result, Some(Ordering::Less)); let result = 1.0.partial_cmp(&1.0); assert_eq!(result, Some(Ordering::Equal)); let result = 2.0.partial_cmp(&1.0); assert_eq!(result, Some(Ordering::Greater)); }
use std::cmp::Ordering;

let result = 1.0.partial_cmp(&2.0);
assert_eq!(result, Some(Ordering::Less));

let result = 1.0.partial_cmp(&1.0);
assert_eq!(result, Some(Ordering::Equal));

let result = 2.0.partial_cmp(&1.0);
assert_eq!(result, Some(Ordering::Greater));

When comparison is impossible:

fn main() { let result = std::f64::NAN.partial_cmp(&1.0); assert_eq!(result, None); }
let result = std::f64::NAN.partial_cmp(&1.0);
assert_eq!(result, None);

Provided Methods

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator.

Examples

fn main() { let result = 1.0 < 2.0; assert_eq!(result, true); let result = 2.0 < 1.0; assert_eq!(result, false); }
let result = 1.0 < 2.0;
assert_eq!(result, true);

let result = 2.0 < 1.0;
assert_eq!(result, false);

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator.

Examples

fn main() { let result = 1.0 <= 2.0; assert_eq!(result, true); let result = 2.0 <= 2.0; assert_eq!(result, true); }
let result = 1.0 <= 2.0;
assert_eq!(result, true);

let result = 2.0 <= 2.0;
assert_eq!(result, true);

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator.

Examples

fn main() { let result = 1.0 > 2.0; assert_eq!(result, false); let result = 2.0 > 2.0; assert_eq!(result, false); }
let result = 1.0 > 2.0;
assert_eq!(result, false);

let result = 2.0 > 2.0;
assert_eq!(result, false);

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator.

Examples

fn main() { let result = 2.0 >= 1.0; assert_eq!(result, true); let result = 2.0 >= 2.0; assert_eq!(result, true); }
let result = 2.0 >= 1.0;
assert_eq!(result, true);

let result = 2.0 >= 2.0;
assert_eq!(result, true);

Implementors

Trait std::cmp::Eq1.0.0 [] [src]

pub trait Eq: PartialEq<Self> { }

Trait for equality comparisons which are equivalence relations.

This means, that in addition to a == b and a != b being strict inverses, the equality must be (for all a, b and c):

  • reflexive: a == a;
  • symmetric: a == b implies b == a; and
  • transitive: a == b and b == c implies a == c.

This property cannot be checked by the compiler, and therefore Eq implies PartialEq, and has no extra methods.

Derivable

This trait can be used with #[derive]. When derived, because Eq has no extra methods, it is only informing the compiler that this is an equivalence relation rather than a partial equivalence relation. Note that the derive strategy requires all fields are PartialEq, which isn't always desired.

How can I implement Eq?

If you cannot use the derive strategy, specify that your type implements Eq, which has no methods:

fn main() { enum BookFormat { Paperback, Hardback, Ebook } struct Book { isbn: i32, format: BookFormat, } impl PartialEq for Book { fn eq(&self, other: &Book) -> bool { self.isbn == other.isbn } } impl Eq for Book {} }
enum BookFormat { Paperback, Hardback, Ebook }
struct Book {
    isbn: i32,
    format: BookFormat,
}
impl PartialEq for Book {
    fn eq(&self, other: &Book) -> bool {
        self.isbn == other.isbn
    }
}
impl Eq for Book {}

Implementors

  • impl<T> Eq for Wrapping<T> where T: Eq
  • impl<T> Eq for NonZero<T> where T: Zeroable + Eq
  • impl<T> Eq for *const T where T: ?Sized
  • impl<T> Eq for *mut T where T: ?Sized
  • impl<Ret> Eq for fn() -> Ret
  • impl<Ret> Eq for extern fn() -> Ret
  • impl<Ret> Eq for unsafe fn() -> Ret
  • impl<Ret> Eq for unsafe extern fn() -> Ret
  • impl<Ret, A> Eq for fn(A) -> Ret
  • impl<Ret, A> Eq for extern fn(A) -> Ret
  • impl<Ret, A> Eq for unsafe fn(A) -> Ret
  • impl<Ret, A> Eq for unsafe extern fn(A) -> Ret
  • impl<Ret, A, B> Eq for fn(A, B) -> Ret
  • impl<Ret, A, B> Eq for extern fn(A, B) -> Ret
  • impl<Ret, A, B> Eq for unsafe fn(A, B) -> Ret
  • impl<Ret, A, B> Eq for unsafe extern fn(A, B) -> Ret
  • impl<Ret, A, B, C> Eq for fn(A, B, C) -> Ret
  • impl<Ret, A, B, C> Eq for extern fn(A, B, C) -> Ret
  • impl<Ret, A, B, C> Eq for unsafe fn(A, B, C) -> Ret
  • impl<Ret, A, B, C> Eq for unsafe extern fn(A, B, C) -> Ret
  • impl<Ret, A, B, C, D> Eq for fn(A, B, C, D) -> Ret
  • impl<Ret, A, B, C, D> Eq for extern fn(A, B, C, D) -> Ret
  • impl<Ret, A, B, C, D> Eq for unsafe fn(A, B, C, D) -> Ret
  • impl<Ret, A, B, C, D> Eq for unsafe extern fn(A, B, C, D) -> Ret
  • impl<Ret, A, B, C, D, E> Eq for fn(A, B, C, D, E) -> Ret
  • impl<Ret, A, B, C, D, E> Eq for extern fn(A, B, C, D, E) -> Ret
  • impl<Ret, A, B, C, D, E> Eq for unsafe fn(A, B, C, D, E) -> Ret
  • impl<Ret, A, B, C, D, E> Eq for unsafe extern fn(A, B, C, D, E) -> Ret
  • impl<Ret, A, B, C, D, E, F> Eq for fn(A, B, C, D, E, F) -> Ret
  • impl<Ret, A, B, C, D, E, F> Eq for extern fn(A, B, C, D, E, F) -> Ret
  • impl<Ret, A, B, C, D, E, F> Eq for unsafe fn(A, B, C, D, E, F) -> Ret
  • impl<Ret, A, B, C, D, E, F> Eq for unsafe extern fn(A, B, C, D, E, F) -> Ret
  • impl<Ret, A, B, C, D, E, F, G> Eq for fn(A, B, C, D, E, F, G) -> Ret
  • impl<Ret, A, B, C, D, E, F, G> Eq for extern fn(A, B, C, D, E, F, G) -> Ret
  • impl<Ret, A, B, C, D, E, F, G> Eq for unsafe fn(A, B, C, D, E, F, G) -> Ret
  • impl<Ret, A, B, C, D, E, F, G> Eq for unsafe extern fn(A, B, C, D, E, F, G) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H> Eq for fn(A, B, C, D, E, F, G, H) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H> Eq for extern fn(A, B, C, D, E, F, G, H) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H> Eq for unsafe fn(A, B, C, D, E, F, G, H) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H> Eq for unsafe extern fn(A, B, C, D, E, F, G, H) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I> Eq for fn(A, B, C, D, E, F, G, H, I) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I> Eq for extern fn(A, B, C, D, E, F, G, H, I) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I> Eq for unsafe fn(A, B, C, D, E, F, G, H, I) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I> Eq for unsafe extern fn(A, B, C, D, E, F, G, H, I) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J> Eq for fn(A, B, C, D, E, F, G, H, I, J) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J> Eq for extern fn(A, B, C, D, E, F, G, H, I, J) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J> Eq for unsafe fn(A, B, C, D, E, F, G, H, I, J) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J> Eq for unsafe extern fn(A, B, C, D, E, F, G, H, I, J) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K> Eq for fn(A, B, C, D, E, F, G, H, I, J, K) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K> Eq for extern fn(A, B, C, D, E, F, G, H, I, J, K) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K> Eq for unsafe fn(A, B, C, D, E, F, G, H, I, J, K) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K> Eq for unsafe extern fn(A, B, C, D, E, F, G, H, I, J, K) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K, L> Eq for fn(A, B, C, D, E, F, G, H, I, J, K, L) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K, L> Eq for extern fn(A, B, C, D, E, F, G, H, I, J, K, L) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K, L> Eq for unsafe fn(A, B, C, D, E, F, G, H, I, J, K, L) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K, L> Eq for unsafe extern fn(A, B, C, D, E, F, G, H, I, J, K, L) -> Ret
  • impl<T> Eq for PhantomData<T> where T: ?Sized
  • impl Eq for RangeFull
  • impl<Idx> Eq for Range<Idx> where Idx: Eq
  • impl<Idx> Eq for RangeFrom<Idx> where Idx: Eq
  • impl<Idx> Eq for RangeTo<Idx> where Idx: Eq
  • impl<Idx> Eq for RangeInclusive<Idx> where Idx: Eq
  • impl<Idx> Eq for RangeToInclusive<Idx> where Idx: Eq
  • impl Eq for Ordering
  • impl Eq for ()
  • impl Eq for bool
  • impl Eq for char
  • impl Eq for usize
  • impl Eq for u8
  • impl Eq for u16
  • impl Eq for u32
  • impl Eq for u64
  • impl Eq for isize
  • impl Eq for i8
  • impl Eq for i16
  • impl Eq for i32
  • impl Eq for i64
  • impl<'a, A> Eq for &'a A where A: Eq + ?Sized
  • impl<'a, A> Eq for &'a mut A where A: Eq + ?Sized
  • impl Eq for TypeId
  • impl<T> Eq for [T; 0] where T: Eq
  • impl<T> Eq for [T; 1] where T: Eq
  • impl<T> Eq for [T; 2] where T: Eq
  • impl<T> Eq for [T; 3] where T: Eq
  • impl<T> Eq for [T; 4] where T: Eq
  • impl<T> Eq for [T; 5] where T: Eq
  • impl<T> Eq for [T; 6] where T: Eq
  • impl<T> Eq for [T; 7] where T: Eq
  • impl<T> Eq for [T; 8] where T: Eq
  • impl<T> Eq for [T; 9] where T: Eq
  • impl<T> Eq for [T; 10] where T: Eq
  • impl<T> Eq for [T; 11] where T: Eq
  • impl<T> Eq for [T; 12] where T: Eq
  • impl<T> Eq for [T; 13] where T: Eq
  • impl<T> Eq for [T; 14] where T: Eq
  • impl<T> Eq for [T; 15] where T: Eq
  • impl<T> Eq for [T; 16] where T: Eq
  • impl<T> Eq for [T; 17] where T: Eq
  • impl<T> Eq for [T; 18] where T: Eq
  • impl<T> Eq for [T; 19] where T: Eq
  • impl<T> Eq for [T; 20] where T: Eq
  • impl<T> Eq for [T; 21] where T: Eq
  • impl<T> Eq for [T; 22] where T: Eq
  • impl<T> Eq for [T; 23] where T: Eq
  • impl<T> Eq for [T; 24] where T: Eq
  • impl<T> Eq for [T; 25] where T: Eq
  • impl<T> Eq for [T; 26] where T: Eq
  • impl<T> Eq for [T; 27] where T: Eq
  • impl<T> Eq for [T; 28] where T: Eq
  • impl<T> Eq for [T; 29] where T: Eq
  • impl<T> Eq for [T; 30] where T: Eq
  • impl<T> Eq for [T; 31] where T: Eq
  • impl<T> Eq for [T; 32] where T: Eq
  • impl<T> Eq for Cell<T> where T: Copy + Eq
  • impl Eq for BorrowState
  • impl<T> Eq for RefCell<T> where T: Eq + ?Sized
  • impl<T> Eq for Option<T> where T: Eq
  • impl<T, E> Eq for Result<T, E> where E: Eq, T: Eq
  • impl<T> Eq for [T] where T: Eq
  • impl Eq for SearchStep
  • impl Eq for Utf8Error
  • impl Eq for str
  • impl Eq for Error
  • impl<A> Eq for (A,) where A: Eq
  • impl<A, B> Eq for (A, B) where A: Eq, B: Eq
  • impl<A, B, C> Eq for (A, B, C) where A: Eq, B: Eq, C: Eq
  • impl<A, B, C, D> Eq for (A, B, C, D) where A: Eq, B: Eq, C: Eq, D: Eq
  • impl<A, B, C, D, E> Eq for (A, B, C, D, E) where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq
  • impl<A, B, C, D, E, F> Eq for (A, B, C, D, E, F) where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq, F: Eq
  • impl<A, B, C, D, E, F, G> Eq for (A, B, C, D, E, F, G) where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq, F: Eq, G: Eq
  • impl<A, B, C, D, E, F, G, H> Eq for (A, B, C, D, E, F, G, H) where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq, F: Eq, G: Eq, H: Eq
  • impl<A, B, C, D, E, F, G, H, I> Eq for (A, B, C, D, E, F, G, H, I) where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq, F: Eq, G: Eq, H: Eq, I: Eq
  • impl<A, B, C, D, E, F, G, H, I, J> Eq for (A, B, C, D, E, F, G, H, I, J) where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq, F: Eq, G: Eq, H: Eq, I: Eq, J: Eq
  • impl<A, B, C, D, E, F, G, H, I, J, K> Eq for (A, B, C, D, E, F, G, H, I, J, K) where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq, F: Eq, G: Eq, H: Eq, I: Eq, J: Eq, K: Eq
  • impl<A, B, C, D, E, F, G, H, I, J, K, L> Eq for (A, B, C, D, E, F, G, H, I, J, K, L) where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq, F: Eq, G: Eq, H: Eq, I: Eq, J: Eq, K: Eq, L: Eq
  • impl<T> Eq for Box<T> where T: Eq + ?Sized
  • impl<T> Eq for Arc<T> where T: Eq + ?Sized
  • impl<T> Eq for Rc<T> where T: Eq + ?Sized
  • impl<K, V> Eq for BTreeMap<K, V> where K: Eq, V: Eq
  • impl<T> Eq for BTreeSet<T> where T: Eq
  • impl<'a, B> Eq for Cow<'a, B> where B: Eq + ToOwned + ?Sized
  • impl<E> Eq for EnumSet<E> where E: Eq
  • impl<A> Eq for LinkedList<A> where A: Eq
  • impl Eq for String
  • impl Eq for ParseError
  • impl<T> Eq for Vec<T> where T: Eq
  • impl<A> Eq for VecDeque<A> where A: Eq
  • impl<T> Eq for Bound<T> where T: Eq
  • impl Eq for DecodeUtf16Error
  • impl Eq for LocalKeyState
  • impl<K, V, S> Eq for HashMap<K, V, S> where K: Eq + Hash, V: Eq, S: BuildHasher
  • impl<T, S> Eq for HashSet<T, S> where T: Eq + Hash, S: BuildHasher
  • impl Eq for VarError
  • impl Eq for CString
  • impl Eq for CStr
  • impl Eq for OsString
  • impl Eq for OsStr
  • impl Eq for Permissions
  • impl Eq for FileType
  • impl Eq for ErrorKind
  • impl Eq for SeekFrom
  • impl Eq for IpAddr
  • impl Eq for Ipv6MulticastScope
  • impl Eq for Ipv4Addr
  • impl Eq for Ipv6Addr
  • impl Eq for SocketAddr
  • impl Eq for SocketAddrV4
  • impl Eq for SocketAddrV6
  • impl<'a> Eq for Prefix<'a>
  • impl<'a> Eq for PrefixComponent<'a>
  • impl<'a> Eq for Component<'a>
  • impl<'a> Eq for Components<'a>
  • impl Eq for PathBuf
  • impl Eq for StripPrefixError
  • impl Eq for Path
  • impl Eq for Output
  • impl Eq for ExitStatus
  • impl<T: Eq> Eq for SendError<T>
  • impl Eq for RecvError
  • impl Eq for TryRecvError
  • impl Eq for RecvTimeoutError
  • impl<T: Eq> Eq for TrySendError<T>
  • impl Eq for WaitTimeoutResult
  • impl Eq for Duration
  • impl Eq for Instant
  • impl Eq for SystemTime

Trait std::cmp::Ord1.0.0 [] [src]

pub trait Ord: Eq + PartialOrd<Self> {
    fn cmp(&self, other: &Self) -> Ordering;
}

Trait for types that form a total order.

An order is a total order if it is (for all a, b and c):

  • total and antisymmetric: exactly one of a < b, a == b or a > b is true; and
  • transitive, a < b and b < c implies a < c. The same must hold for both == and >.

Derivable

This trait can be used with #[derive]. When derived, it will produce a lexicographic ordering based on the top-to-bottom declaration order of the struct's members.

How can I implement Ord?

Ord requires that the type also be PartialOrd and Eq (which requires PartialEq).

Then you must define an implementation for cmp(). You may find it useful to use cmp() on your type's fields.

Here's an example where you want to sort people by height only, disregarding id and name:

fn main() { use std::cmp::Ordering; #[derive(Eq)] struct Person { id: u32, name: String, height: u32, } impl Ord for Person { fn cmp(&self, other: &Person) -> Ordering { self.height.cmp(&other.height) } } impl PartialOrd for Person { fn partial_cmp(&self, other: &Person) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialEq for Person { fn eq(&self, other: &Person) -> bool { self.height == other.height } } }
use std::cmp::Ordering;

#[derive(Eq)]
struct Person {
    id: u32,
    name: String,
    height: u32,
}

impl Ord for Person {
    fn cmp(&self, other: &Person) -> Ordering {
        self.height.cmp(&other.height)
    }
}

impl PartialOrd for Person {
    fn partial_cmp(&self, other: &Person) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Person {
    fn eq(&self, other: &Person) -> bool {
        self.height == other.height
    }
}

Required Methods

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other.

By convention, self.cmp(&other) returns the ordering matching the expression self <operator> other if true.

Examples

fn main() { use std::cmp::Ordering; assert_eq!(5.cmp(&10), Ordering::Less); assert_eq!(10.cmp(&5), Ordering::Greater); assert_eq!(5.cmp(&5), Ordering::Equal); }
use std::cmp::Ordering;

assert_eq!(5.cmp(&10), Ordering::Less);
assert_eq!(10.cmp(&5), Ordering::Greater);
assert_eq!(5.cmp(&5), Ordering::Equal);

Implementors

  • impl<T> Ord for Wrapping<T> where T: Ord
  • impl<T> Ord for NonZero<T> where T: Zeroable + Ord
  • impl<Ret> Ord for fn() -> Ret
  • impl<Ret> Ord for extern fn() -> Ret
  • impl<Ret> Ord for unsafe fn() -> Ret
  • impl<Ret> Ord for unsafe extern fn() -> Ret
  • impl<Ret, A> Ord for fn(A) -> Ret
  • impl<Ret, A> Ord for extern fn(A) -> Ret
  • impl<Ret, A> Ord for unsafe fn(A) -> Ret
  • impl<Ret, A> Ord for unsafe extern fn(A) -> Ret
  • impl<Ret, A, B> Ord for fn(A, B) -> Ret
  • impl<Ret, A, B> Ord for extern fn(A, B) -> Ret
  • impl<Ret, A, B> Ord for unsafe fn(A, B) -> Ret
  • impl<Ret, A, B> Ord for unsafe extern fn(A, B) -> Ret
  • impl<Ret, A, B, C> Ord for fn(A, B, C) -> Ret
  • impl<Ret, A, B, C> Ord for extern fn(A, B, C) -> Ret
  • impl<Ret, A, B, C> Ord for unsafe fn(A, B, C) -> Ret
  • impl<Ret, A, B, C> Ord for unsafe extern fn(A, B, C) -> Ret
  • impl<Ret, A, B, C, D> Ord for fn(A, B, C, D) -> Ret
  • impl<Ret, A, B, C, D> Ord for extern fn(A, B, C, D) -> Ret
  • impl<Ret, A, B, C, D> Ord for unsafe fn(A, B, C, D) -> Ret
  • impl<Ret, A, B, C, D> Ord for unsafe extern fn(A, B, C, D) -> Ret
  • impl<Ret, A, B, C, D, E> Ord for fn(A, B, C, D, E) -> Ret
  • impl<Ret, A, B, C, D, E> Ord for extern fn(A, B, C, D, E) -> Ret
  • impl<Ret, A, B, C, D, E> Ord for unsafe fn(A, B, C, D, E) -> Ret
  • impl<Ret, A, B, C, D, E> Ord for unsafe extern fn(A, B, C, D, E) -> Ret
  • impl<Ret, A, B, C, D, E, F> Ord for fn(A, B, C, D, E, F) -> Ret
  • impl<Ret, A, B, C, D, E, F> Ord for extern fn(A, B, C, D, E, F) -> Ret
  • impl<Ret, A, B, C, D, E, F> Ord for unsafe fn(A, B, C, D, E, F) -> Ret
  • impl<Ret, A, B, C, D, E, F> Ord for unsafe extern fn(A, B, C, D, E, F) -> Ret
  • impl<Ret, A, B, C, D, E, F, G> Ord for fn(A, B, C, D, E, F, G) -> Ret
  • impl<Ret, A, B, C, D, E, F, G> Ord for extern fn(A, B, C, D, E, F, G) -> Ret
  • impl<Ret, A, B, C, D, E, F, G> Ord for unsafe fn(A, B, C, D, E, F, G) -> Ret
  • impl<Ret, A, B, C, D, E, F, G> Ord for unsafe extern fn(A, B, C, D, E, F, G) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H> Ord for fn(A, B, C, D, E, F, G, H) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H> Ord for extern fn(A, B, C, D, E, F, G, H) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H> Ord for unsafe fn(A, B, C, D, E, F, G, H) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H> Ord for unsafe extern fn(A, B, C, D, E, F, G, H) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I> Ord for fn(A, B, C, D, E, F, G, H, I) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I> Ord for extern fn(A, B, C, D, E, F, G, H, I) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I> Ord for unsafe fn(A, B, C, D, E, F, G, H, I) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I> Ord for unsafe extern fn(A, B, C, D, E, F, G, H, I) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J> Ord for fn(A, B, C, D, E, F, G, H, I, J) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J> Ord for extern fn(A, B, C, D, E, F, G, H, I, J) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J> Ord for unsafe fn(A, B, C, D, E, F, G, H, I, J) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J> Ord for unsafe extern fn(A, B, C, D, E, F, G, H, I, J) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K> Ord for fn(A, B, C, D, E, F, G, H, I, J, K) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K> Ord for extern fn(A, B, C, D, E, F, G, H, I, J, K) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K> Ord for unsafe fn(A, B, C, D, E, F, G, H, I, J, K) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K> Ord for unsafe extern fn(A, B, C, D, E, F, G, H, I, J, K) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K, L> Ord for fn(A, B, C, D, E, F, G, H, I, J, K, L) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K, L> Ord for extern fn(A, B, C, D, E, F, G, H, I, J, K, L) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K, L> Ord for unsafe fn(A, B, C, D, E, F, G, H, I, J, K, L) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K, L> Ord for unsafe extern fn(A, B, C, D, E, F, G, H, I, J, K, L) -> Ret
  • impl<T> Ord for *const T where T: ?Sized
  • impl<T> Ord for *mut T where T: ?Sized
  • impl<T> Ord for PhantomData<T> where T: ?Sized
  • impl Ord for Ordering
  • impl Ord for ()
  • impl Ord for bool
  • impl Ord for char
  • impl Ord for usize
  • impl Ord for u8
  • impl Ord for u16
  • impl Ord for u32
  • impl Ord for u64
  • impl Ord for isize
  • impl Ord for i8
  • impl Ord for i16
  • impl Ord for i32
  • impl Ord for i64
  • impl<'a, A> Ord for &'a A where A: Ord + ?Sized
  • impl<'a, A> Ord for &'a mut A where A: Ord + ?Sized
  • impl<T> Ord for [T; 0] where T: Ord
  • impl<T> Ord for [T; 1] where T: Ord
  • impl<T> Ord for [T; 2] where T: Ord
  • impl<T> Ord for [T; 3] where T: Ord
  • impl<T> Ord for [T; 4] where T: Ord
  • impl<T> Ord for [T; 5] where T: Ord
  • impl<T> Ord for [T; 6] where T: Ord
  • impl<T> Ord for [T; 7] where T: Ord
  • impl<T> Ord for [T; 8] where T: Ord
  • impl<T> Ord for [T; 9] where T: Ord
  • impl<T> Ord for [T; 10] where T: Ord
  • impl<T> Ord for [T; 11] where T: Ord
  • impl<T> Ord for [T; 12] where T: Ord
  • impl<T> Ord for [T; 13] where T: Ord
  • impl<T> Ord for [T; 14] where T: Ord
  • impl<T> Ord for [T; 15] where T: Ord
  • impl<T> Ord for [T; 16] where T: Ord
  • impl<T> Ord for [T; 17] where T: Ord
  • impl<T> Ord for [T; 18] where T: Ord
  • impl<T> Ord for [T; 19] where T: Ord
  • impl<T> Ord for [T; 20] where T: Ord
  • impl<T> Ord for [T; 21] where T: Ord
  • impl<T> Ord for [T; 22] where T: Ord
  • impl<T> Ord for [T; 23] where T: Ord
  • impl<T> Ord for [T; 24] where T: Ord
  • impl<T> Ord for [T; 25] where T: Ord
  • impl<T> Ord for [T; 26] where T: Ord
  • impl<T> Ord for [T; 27] where T: Ord
  • impl<T> Ord for [T; 28] where T: Ord
  • impl<T> Ord for [T; 29] where T: Ord
  • impl<T> Ord for [T; 30] where T: Ord
  • impl<T> Ord for [T; 31] where T: Ord
  • impl<T> Ord for [T; 32] where T: Ord
  • impl<T> Ord for Cell<T> where T: Copy + Ord
  • impl<T> Ord for RefCell<T> where T: Ord + ?Sized
  • impl<T> Ord for Option<T> where T: Ord
  • impl<T, E> Ord for Result<T, E> where E: Ord, T: Ord
  • impl<T> Ord for [T] where T: Ord
  • impl Ord for str
  • impl Ord for Error
  • impl<A> Ord for (A,) where A: Ord
  • impl<A, B> Ord for (A, B) where A: Ord, B: Ord
  • impl<A, B, C> Ord for (A, B, C) where A: Ord, B: Ord, C: Ord
  • impl<A, B, C, D> Ord for (A, B, C, D) where A: Ord, B: Ord, C: Ord, D: Ord
  • impl<A, B, C, D, E> Ord for (A, B, C, D, E) where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord
  • impl<A, B, C, D, E, F> Ord for (A, B, C, D, E, F) where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord, F: Ord
  • impl<A, B, C, D, E, F, G> Ord for (A, B, C, D, E, F, G) where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord, F: Ord, G: Ord
  • impl<A, B, C, D, E, F, G, H> Ord for (A, B, C, D, E, F, G, H) where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord, F: Ord, G: Ord, H: Ord
  • impl<A, B, C, D, E, F, G, H, I> Ord for (A, B, C, D, E, F, G, H, I) where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord, F: Ord, G: Ord, H: Ord, I: Ord
  • impl<A, B, C, D, E, F, G, H, I, J> Ord for (A, B, C, D, E, F, G, H, I, J) where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord, F: Ord, G: Ord, H: Ord, I: Ord, J: Ord
  • impl<A, B, C, D, E, F, G, H, I, J, K> Ord for (A, B, C, D, E, F, G, H, I, J, K) where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord, F: Ord, G: Ord, H: Ord, I: Ord, J: Ord, K: Ord
  • impl<A, B, C, D, E, F, G, H, I, J, K, L> Ord for (A, B, C, D, E, F, G, H, I, J, K, L) where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord, F: Ord, G: Ord, H: Ord, I: Ord, J: Ord, K: Ord, L: Ord
  • impl<T> Ord for Box<T> where T: Ord + ?Sized
  • impl<T> Ord for Arc<T> where T: Ord + ?Sized
  • impl<T> Ord for Rc<T> where T: Ord + ?Sized
  • impl<K, V> Ord for BTreeMap<K, V> where K: Ord, V: Ord
  • impl<T> Ord for BTreeSet<T> where T: Ord
  • impl<'a, B> Ord for Cow<'a, B> where B: Ord + ToOwned + ?Sized
  • impl<E> Ord for EnumSet<E> where E: Ord
  • impl<A> Ord for LinkedList<A> where A: Ord
  • impl Ord for String
  • impl<T> Ord for Vec<T> where T: Ord
  • impl<A> Ord for VecDeque<A> where A: Ord
  • impl Ord for CString
  • impl Ord for CStr
  • impl Ord for OsString
  • impl Ord for OsStr
  • impl Ord for IpAddr
  • impl Ord for Ipv4Addr
  • impl Ord for Ipv6Addr
  • impl<'a> Ord for Prefix<'a>
  • impl<'a> Ord for PrefixComponent<'a>
  • impl<'a> Ord for Component<'a>
  • impl<'a> Ord for Components<'a>
  • impl Ord for PathBuf
  • impl Ord for Path
  • impl Ord for Duration
  • impl Ord for Instant
  • impl Ord for SystemTime

Trait std::io::Write1.0.0 [] [src]

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: Arguments) -> Result<()> { ... }
    fn by_ref(&mut self) -> &mut Self where Self: Sized { ... }
}

A trait for objects which are byte-oriented sinks.

Implementors of the Write trait are sometimes called 'writers'.

Writers are defined by two required methods, write() and flush():

  • The write() method will attempt to write some data into the object, returning how many bytes were successfully written.

  • The flush() method is useful for adaptors and explicit buffers themselves for ensuring that all buffered data has been pushed out to the 'true sink'.

Writers are intended to be composable with one another. Many implementors throughout std::io take and provide types which implement the Write trait.

Examples

fn main() { use std::io::prelude::*; use std::fs::File; fn foo() -> std::io::Result<()> { let mut buffer = try!(File::create("foo.txt")); try!(buffer.write(b"some bytes")); Ok(()) } }
use std::io::prelude::*;
use std::fs::File;

let mut buffer = try!(File::create("foo.txt"));

try!(buffer.write(b"some bytes"));

Required Methods

fn write(&mut self, buf: &[u8]) -> Result<usize>

Write a buffer into this object, returning how many bytes were written.

This function will attempt to write the entire contents of buf, but the entire write may not succeed, or the write may also generate an error. A call to write represents at most one attempt to write to any wrapped object.

Calls to write are not guaranteed to block waiting for data to be written, and a write which would otherwise block can be indicated through an Err variant.

If the return value is Ok(n) then it must be guaranteed that 0 <= n <= buf.len(). A return value of 0 typically means that the underlying object is no longer able to accept bytes and will likely not be able to in the future as well, or that the buffer provided is empty.

Errors

Each call to write may generate an I/O error indicating that the operation could not be completed. If an error is returned then no bytes in the buffer were written to this writer.

It is not considered an error if the entire buffer could not be written to this writer.

Examples

fn main() { use std::io::prelude::*; use std::fs::File; fn foo() -> std::io::Result<()> { let mut buffer = try!(File::create("foo.txt")); try!(buffer.write(b"some bytes")); Ok(()) } }
use std::io::prelude::*;
use std::fs::File;

let mut buffer = try!(File::create("foo.txt"));

try!(buffer.write(b"some bytes"));

fn flush(&mut self) -> Result<()>

Flush this output stream, ensuring that all intermediately buffered contents reach their destination.

Errors

It is considered an error if not all bytes could be written due to I/O errors or EOF being reached.

Examples

fn main() { use std::io::prelude::*; use std::io::BufWriter; use std::fs::File; fn foo() -> std::io::Result<()> { let mut buffer = BufWriter::new(try!(File::create("foo.txt"))); try!(buffer.write(b"some bytes")); try!(buffer.flush()); Ok(()) } }
use std::io::prelude::*;
use std::io::BufWriter;
use std::fs::File;

let mut buffer = BufWriter::new(try!(File::create("foo.txt")));

try!(buffer.write(b"some bytes"));
try!(buffer.flush());

Provided Methods

fn write_all(&mut self, buf: &[u8]) -> Result<()>

Attempts to write an entire buffer into this write.

This method will continuously call write while there is more data to write. This method will not return until the entire buffer has been successfully written or an error occurs. The first error generated from this method will be returned.

Errors

This function will return the first error that write returns.

Examples

fn main() { use std::io::prelude::*; use std::fs::File; fn foo() -> std::io::Result<()> { let mut buffer = try!(File::create("foo.txt")); try!(buffer.write_all(b"some bytes")); Ok(()) } }
use std::io::prelude::*;
use std::fs::File;

let mut buffer = try!(File::create("foo.txt"));

try!(buffer.write_all(b"some bytes"));

fn write_fmt(&mut self, fmt: Arguments) -> Result<()>

Writes a formatted string into this writer, returning any error encountered.

This method is primarily used to interface with the format_args! macro, but it is rare that this should explicitly be called. The write! macro should be favored to invoke this method instead.

This function internally uses the write_all method on this trait and hence will continuously write data so long as no errors are received. This also means that partial writes are not indicated in this signature.

Errors

This function will return any I/O error reported while formatting.

Examples

fn main() { use std::io::prelude::*; use std::fs::File; fn foo() -> std::io::Result<()> { let mut buffer = try!(File::create("foo.txt")); // this call try!(write!(buffer, "{:.*}", 2, 1.234567)); // turns into this: try!(buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))); Ok(()) } }
use std::io::prelude::*;
use std::fs::File;

let mut buffer = try!(File::create("foo.txt"));

// this call
try!(write!(buffer, "{:.*}", 2, 1.234567));
// turns into this:
try!(buffer.write_fmt(format_args!("{:.*}", 2, 1.234567)));

fn by_ref(&mut self) -> &mut Self where Self: Sized

Creates a "by reference" adaptor for this instance of Write.

The returned adaptor also implements Write and will simply borrow this current writer.

Examples

fn main() { use std::io::Write; use std::fs::File; fn foo() -> std::io::Result<()> { let mut buffer = try!(File::create("foo.txt")); let reference = buffer.by_ref(); // we can use reference just like our original buffer try!(reference.write_all(b"some bytes")); Ok(()) } }
use std::io::Write;
use std::fs::File;

let mut buffer = try!(File::create("foo.txt"));

let reference = buffer.by_ref();

// we can use reference just like our original buffer
try!(reference.write_all(b"some bytes"));

Implementors

fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where P: FnMut(&Self::Item) -> bool

Searches for an element of an iterator that satisfies a predicate. Read more

A hash map implementation which uses linear probing with Robin Hood bucket stealing.

The hashes are all keyed by the thread-local random number generator on creation by default. This means that the ordering of the keys is randomized, but makes the tables more resistant to denial-of-service attacks (Hash DoS). No guarantees are made to the quality of the random data. The implementation uses the best available random data from your platform at the time of creation. This behavior can be overridden with one of the constructors.

It is required that the keys implement the Eq and Hash traits, although 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 trait, or its equality, as determined by the Eq trait, changes while it is in the map. This is normally only possible through Cell, RefCell, global state, I/O, or unsafe code.

Relevant papers/articles:

  1. Pedro Celis. "Robin Hood Hashing"
  2. Emmanuel Goossaert. "Robin Hood hashing"
  3. Emmanuel Goossaert. "Robin Hood hashing: backward shift deletion"

Examples

fn main() { use std::collections::HashMap; // type inference lets us omit an explicit type signature (which // would be `HashMap<&str, &str>` in this example). let mut book_reviews = HashMap::new(); // review some books. book_reviews.insert("Adventures of Huckleberry Finn", "My favorite book."); book_reviews.insert("Grimms' Fairy Tales", "Masterpiece."); book_reviews.insert("Pride and Prejudice", "Very enjoyable."); book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot."); // check for a specific one. if !book_reviews.contains_key("Les Misérables") { println!("We've got {} reviews, but Les Misérables ain't one.", book_reviews.len()); } // oops, this review has a lot of spelling mistakes, let's delete it. book_reviews.remove("The Adventures of Sherlock Holmes"); // look up the values associated with some keys. let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"]; for book in &to_find { match book_reviews.get(book) { Some(review) => println!("{}: {}", book, review), None => println!("{} is unreviewed.", book) } } // iterate over everything. for (book, review) in &book_reviews { println!("{}: \"{}\"", book, review); } }
use std::collections::HashMap;

// type inference lets us omit an explicit type signature (which
// would be `HashMap<&str, &str>` in this example).
let mut book_reviews = HashMap::new();

// review some books.
book_reviews.insert("Adventures of Huckleberry Finn",    "My favorite book.");
book_reviews.insert("Grimms' Fairy Tales",               "Masterpiece.");
book_reviews.insert("Pride and Prejudice",               "Very enjoyable.");
book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");

// check for a specific one.
if !book_reviews.contains_key("Les Misérables") {
    println!("We've got {} reviews, but Les Misérables ain't one.",
             book_reviews.len());
}

// oops, this review has a lot of spelling mistakes, let's delete it.
book_reviews.remove("The Adventures of Sherlock Holmes");

// look up the values associated with some keys.
let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
for book in &to_find {
    match book_reviews.get(book) {
        Some(review) => println!("{}: {}", book, review),
        None => println!("{} is unreviewed.", book)
    }
}

// iterate over everything.
for (book, review) in &book_reviews {
    println!("{}: \"{}\"", book, review);
}

HashMap also implements an Entry API, which allows for more complex methods of getting, setting, updating and removing keys and their values:

fn main() { use std::collections::HashMap; // type inference lets us omit an explicit type signature (which // would be `HashMap<&str, u8>` in this example). let mut player_stats = HashMap::new(); fn random_stat_buff() -> u8 { // could actually return some random value here - let's just return // some fixed value for now 42 } // insert a key only if it doesn't already exist player_stats.entry("health").or_insert(100); // insert a key using a function that provides a new value only if it // doesn't already exist player_stats.entry("defence").or_insert_with(random_stat_buff); // update a key, guarding against the key possibly not being set let stat = player_stats.entry("attack").or_insert(100); *stat += random_stat_buff(); }
use std::collections::HashMap;

// type inference lets us omit an explicit type signature (which
// would be `HashMap<&str, u8>` in this example).
let mut player_stats = HashMap::new();

fn random_stat_buff() -> u8 {
    // could actually return some random value here - let's just return
    // some fixed value for now
    42
}

// insert a key only if it doesn't already exist
player_stats.entry("health").or_insert(100);

// insert a key using a function that provides a new value only if it
// doesn't already exist
player_stats.entry("defence").or_insert_with(random_stat_buff);

// update a key, guarding against the key possibly not being set
let stat = player_stats.entry("attack").or_insert(100);
*stat += random_stat_buff();

The easiest way to use HashMap with a custom type as key is to derive Eq and Hash. We must also derive PartialEq.

fn main() { use std::collections::HashMap; #[derive(Hash, Eq, PartialEq, Debug)] struct Viking { name: String, country: String, } impl Viking { /// Create a new Viking. fn new(name: &str, country: &str) -> Viking { Viking { name: name.to_string(), country: country.to_string() } } } // Use a HashMap to store the vikings' health points. let mut vikings = HashMap::new(); vikings.insert(Viking::new("Einar", "Norway"), 25); vikings.insert(Viking::new("Olaf", "Denmark"), 24); vikings.insert(Viking::new("Harald", "Iceland"), 12); // Use derived implementation to print the status of the vikings. for (viking, health) in &vikings { println!("{:?} has {} hp", viking, health); } }
use std::collections::HashMap;

#[derive(Hash, Eq, PartialEq, Debug)]
struct Viking {
    name: String,
    country: String,
}

impl Viking {
    /// Create a new Viking.
    fn new(name: &str, country: &str) -> Viking {
        Viking { name: name.to_string(), country: country.to_string() }
    }
}

// Use a HashMap to store the vikings' health points.
let mut vikings = HashMap::new();

vikings.insert(Viking::new("Einar", "Norway"), 25);
vikings.insert(Viking::new("Olaf", "Denmark"), 24);
vikings.insert(Viking::new("Harald", "Iceland"), 12);

// Use derived implementation to print the status of the vikings.
for (viking, health) in &vikings {
    println!("{:?} has {} hp", viking, health);
}

fn new() -> HashMap<K, V, RandomState>

Creates an empty HashMap.

Examples

fn main() { use std::collections::HashMap; let mut map: HashMap<&str, isize> = HashMap::new(); }
use std::collections::HashMap;
let mut map: HashMap<&str, isize> = HashMap::new();

fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState>

Creates an empty hash map with the given initial capacity.

Examples

fn main() { use std::collections::HashMap; let mut map: HashMap<&str, isize> = HashMap::with_capacity(10); }
use std::collections::HashMap;
let mut map: HashMap<&str, isize> = HashMap::with_capacity(10);

fn clone(&self) -> HashMap<K, V, S>

Returns a copy of the value. Read more

fn index(&self, index: &Q) -> &V

The method for the indexing (Foo[Bar]) operation

fn len(&self) -> usize

Returns the number of elements in the map.

Examples

fn main() { use std::collections::HashMap; let mut a = HashMap::new(); assert_eq!(a.len(), 0); a.insert(1, "a"); assert_eq!(a.len(), 1); }
use std::collections::HashMap;

let mut a = HashMap::new();
assert_eq!(a.len(), 0);
a.insert(1, "a");
assert_eq!(a.len(), 1);

fn iter(&self) -> Iter<K, V>

An iterator visiting all key-value pairs in arbitrary order. Iterator element type is (&'a K, &'a V).

Examples

fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); for (key, val) in map.iter() { println!("key: {} val: {}", key, val); } }
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);

for (key, val) in map.iter() {
    println!("key: {} val: {}", key, val);
}

fn iter_mut(&mut self) -> IterMut<K, V>

An iterator visiting all key-value pairs in arbitrary order, with mutable references to the values. Iterator element type is (&'a K, &'a mut V).

Examples

fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); // Update all values for (_, val) in map.iter_mut() { *val *= 2; } for (key, val) in &map { println!("key: {} val: {}", key, val); } }
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);

// Update all values
for (_, val) in map.iter_mut() {
    *val *= 2;
}

for (key, val) in &map {
    println!("key: {} val: {}", key, val);
}

fn into_iter(self) -> Iter<'a, K, V>

Creates an iterator from a value. Read more

fn keys(&self) -> Keys<K, V>

An iterator visiting all keys in arbitrary order. Iterator element type is &'a K.

Examples

fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); for key in map.keys() { println!("{}", key); } }
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);

for key in map.keys() {
    println!("{}", key);
}

fn values(&self) -> Values<K, V>

An iterator visiting all values in arbitrary order. Iterator element type is &'a V.

Examples

fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); for val in map.values() { println!("{}", val); } }
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);

for val in map.values() {
    println!("{}", val);
}

fn values_mut(&mut self) -> ValuesMut<K, V>
1.10.0

An iterator visiting all values mutably in arbitrary order. Iterator element type is &'a mut V.

Examples

fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); for val in map.values_mut() { *val = *val + 10; } for val in map.values() { print!("{}", val); } }
use std::collections::HashMap;

let mut map = HashMap::new();

map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);

for val in map.values_mut() {
    *val = *val + 10;
}

for val in map.values() {
    print!("{}", val);
}

fn is_empty(&self) -> bool

Returns true if the map contains no elements.

Examples

fn main() { use std::collections::HashMap; let mut a = HashMap::new(); assert!(a.is_empty()); a.insert(1, "a"); assert!(!a.is_empty()); }
use std::collections::HashMap;

let mut a = HashMap::new();
assert!(a.is_empty());
a.insert(1, "a");
assert!(!a.is_empty());

fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool where K: Borrow<Q>, Q: Hash + Eq

Returns true if the map contains a value for the specified key.

The key may be any borrowed form of the map's key type, but Hash and Eq on the borrowed form must match those for the key type.

Examples

fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.contains_key(&1), true); assert_eq!(map.contains_key(&2), false); }
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.contains_key(&1), true);
assert_eq!(map.contains_key(&2), false);

fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> where K: Borrow<Q>, Q: Hash + Eq

Returns a reference to the value corresponding to the key.

The key may be any borrowed form of the map's key type, but Hash and Eq on the borrowed form must match those for the key type.

Examples

fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); }
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.get(&2), None);

fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V> where K: Borrow<Q>, Q: Hash + Eq

Returns a mutable reference to the value corresponding to the key.

The key may be any borrowed form of the map's key type, but Hash and Eq on the borrowed form must match those for the key type.

Examples

fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); if let Some(x) = map.get_mut(&1) { *x = "b"; } assert_eq!(map[&1], "b"); }
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
if let Some(x) = map.get_mut(&1) {
    *x = "b";
}
assert_eq!(map[&1], "b");

fn entry(&mut self, key: K) -> Entry<K, V>

Gets the given key's corresponding entry in the map for in-place manipulation.

Examples

fn main() { use std::collections::HashMap; let mut letters = HashMap::new(); for ch in "a short treatise on fungi".chars() { let counter = letters.entry(ch).or_insert(0); *counter += 1; } assert_eq!(letters[&'s'], 2); assert_eq!(letters[&'t'], 3); assert_eq!(letters[&'u'], 1); assert_eq!(letters.get(&'y'), None); }
use std::collections::HashMap;

let mut letters = HashMap::new();

for ch in "a short treatise on fungi".chars() {
    let counter = letters.entry(ch).or_insert(0);
    *counter += 1;
}

assert_eq!(letters[&'s'], 2);
assert_eq!(letters[&'t'], 3);
assert_eq!(letters[&'u'], 1);
assert_eq!(letters.get(&'y'), None);

fn drain(&mut self) -> Drain<K, V>
1.6.0

Clears the map, returning all key-value pairs as an iterator. Keeps the allocated memory for reuse.

Examples

fn main() { use std::collections::HashMap; let mut a = HashMap::new(); a.insert(1, "a"); a.insert(2, "b"); for (k, v) in a.drain().take(1) { assert!(k == 1 || k == 2); assert!(v == "a" || v == "b"); } assert!(a.is_empty()); }
use std::collections::HashMap;

let mut a = HashMap::new();
a.insert(1, "a");
a.insert(2, "b");

for (k, v) in a.drain().take(1) {
    assert!(k == 1 || k == 2);
    assert!(v == "a" || v == "b");
}

assert!(a.is_empty());

fn clear(&mut self)

Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.

Examples

fn main() { use std::collections::HashMap; let mut a = HashMap::new(); a.insert(1, "a"); a.clear(); assert!(a.is_empty()); }
use std::collections::HashMap;

let mut a = HashMap::new();
a.insert(1, "a");
a.clear();
assert!(a.is_empty());

fn extend<T: IntoIterator<Item=(K, V)>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more

fn extend<T: IntoIterator<Item=(&'a K, &'a V)>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more

fn insert(&mut self, k: K, v: V) -> Option<V>

Inserts a key-value pair into the map.

If the map did not have this key present, None is returned.

If the map did have this key present, the value is updated, and the old value is returned. The key is not updated, though; this matters for types that can be == without being identical. See the module-level documentation for more.

Examples

fn main() { use std::collections::HashMap; let mut map = HashMap::new(); assert_eq!(map.insert(37, "a"), None); assert_eq!(map.is_empty(), false); map.insert(37, "b"); assert_eq!(map.insert(37, "c"), Some("b")); assert_eq!(map[&37], "c"); }
use std::collections::HashMap;

let mut map = HashMap::new();
assert_eq!(map.insert(37, "a"), None);
assert_eq!(map.is_empty(), false);

map.insert(37, "b");
assert_eq!(map.insert(37, "c"), Some("b"));
assert_eq!(map[&37], "c");

fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V> where K: Borrow<Q>, Q: Hash + Eq

Removes a key from the map, returning the value at the key if the key was previously in the map.

The key may be any borrowed form of the map's key type, but Hash and Eq on the borrowed form must match those for the key type.

Examples

fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.remove(&1), Some("a")); assert_eq!(map.remove(&1), None); }
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.remove(&1), Some("a"));
assert_eq!(map.remove(&1), None);

fn from_iter<T: IntoIterator<Item=(K, V)>>(iter: T) -> HashMap<K, V, S>

Creates a value from an iterator. Read more

fn capacity(&self) -> usize

Returns the number of elements the map can hold without reallocating.

This number is a lower bound; the HashMap<K, V> might be able to hold more, but is guaranteed to be able to hold at least this many.

Examples

fn main() { use std::collections::HashMap; let map: HashMap<isize, isize> = HashMap::with_capacity(100); assert!(map.capacity() >= 100); }
use std::collections::HashMap;
let map: HashMap<isize, isize> = HashMap::with_capacity(100);
assert!(map.capacity() >= 100);

fn reserve(&mut self, additional: usize)

Reserves capacity for at least additional more elements to be inserted in the HashMap. The collection may reserve more space to avoid frequent reallocations.

Panics

Panics if the new allocation size overflows usize.

Examples

fn main() { use std::collections::HashMap; let mut map: HashMap<&str, isize> = HashMap::new(); map.reserve(10); }
use std::collections::HashMap;
let mut map: HashMap<&str, isize> = HashMap::new();
map.reserve(10);

fn shrink_to_fit(&mut self)

Shrinks the capacity of the map 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

fn main() { use std::collections::HashMap; let mut map: HashMap<isize, isize> = HashMap::with_capacity(100); map.insert(1, 2); map.insert(3, 4); assert!(map.capacity() >= 100); map.shrink_to_fit(); assert!(map.capacity() >= 2); }
use std::collections::HashMap;

let mut map: HashMap<isize, isize> = HashMap::with_capacity(100);
map.insert(1, 2);
map.insert(3, 4);
assert!(map.capacity() >= 100);
map.shrink_to_fit();
assert!(map.capacity() >= 2);

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

fn eq(&self, other: &HashMap<K, V, S>) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &Rhs) -> bool

This method tests for !=.

fn with_hasher(hash_builder: S) -> HashMap<K, V, S>
1.7.0

Creates an empty hashmap which will use the given hash builder to hash keys.

The created map has the default initial capacity.

Warning: hash_builder is normally randomly generated, and is designed to allow HashMaps 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.

Examples

fn main() { use std::collections::HashMap; use std::collections::hash_map::RandomState; let s = RandomState::new(); let mut map = HashMap::with_hasher(s); map.insert(1, 2); }
use std::collections::HashMap;
use std::collections::hash_map::RandomState;

let s = RandomState::new();
let mut map = HashMap::with_hasher(s);
map.insert(1, 2);

fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S>
1.7.0

Creates an empty HashMap with space for at least capacity elements, using hasher to hash the keys.

Warning: hasher is normally randomly generated, and is designed to allow HashMaps 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.

Examples

fn main() { use std::collections::HashMap; use std::collections::hash_map::RandomState; let s = RandomState::new(); let mut map = HashMap::with_capacity_and_hasher(10, s); map.insert(1, 2); }
use std::collections::HashMap;
use std::collections::hash_map::RandomState;

let s = RandomState::new();
let mut map = HashMap::with_capacity_and_hasher(10, s);
map.insert(1, 2);

fn hasher(&self) -> &S
1.9.0

Returns a reference to the map's hasher.

impl<K: Clone, V: Clone, S: Clone> Clone for HashMap<K, V, S>
[src]

fn clone(&self) -> HashMap<K, V, S>

Returns a copy of the value. Read more

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

impl<K, V, S> PartialEq for HashMap<K, V, S> where K: Eq + Hash, V: PartialEq, S: BuildHasher
[src]

fn eq(&self, other: &HashMap<K, V, S>) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &Rhs) -> bool

This method tests for !=.

impl<K, V, S> Debug for HashMap<K, V, S> where K: Eq + Hash + Debug, V: Debug, S: BuildHasher
[src]

fn fmt(&self, f: &mut Formatter) -> Result

Formats the value using the given formatter.

impl<K, V, S> Default for HashMap<K, V, S> where K: Eq + Hash, S: BuildHasher + Default
[src]

fn default() -> HashMap<K, V, S>

Returns the "default value" for a type. Read more

impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S> where K: Eq + Hash + Borrow<Q>, Q: Eq + Hash, S: BuildHasher
[src]

type Output = V

The returned type after indexing

fn index(&self, index: &Q) -> &V

The method for the indexing (Foo[Bar]) operation

impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> where K: Eq + Hash, S: BuildHasher
[src]

type Item = (&'a K, &'a V)

The type of the elements being iterated over.

type IntoIter = Iter<'a, K, V>

Which kind of iterator are we turning this into?

fn into_iter(self) -> Iter<'a, K, V>

Creates an iterator from a value. Read more

impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> where K: Eq + Hash, S: BuildHasher
[src]

type Item = (&'a K, &'a mut V)

The type of the elements being iterated over.

type IntoIter = IterMut<'a, K, V>

Which kind of iterator are we turning this into?

fn into_iter(self) -> IterMut<'a, K, V>

Creates an iterator from a value. Read more

impl<K, V, S> IntoIterator for HashMap<K, V, S> where K: Eq + Hash, S: BuildHasher
[src]

type Item = (K, V)

The type of the elements being iterated over.

type IntoIter = IntoIter<K, V>

Which kind of iterator are we turning this into?

fn into_iter(self) -> IntoIter<K, V>

Creates a consuming iterator, that is, one that moves each key-value pair out of the map in arbitrary order. The map cannot be used after calling this.

Examples

fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); // Not possible with .iter() let vec: Vec<(&str, isize)> = map.into_iter().collect(); }
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);

// Not possible with .iter()
let vec: Vec<(&str, isize)> = map.into_iter().collect();

impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S> where K: Eq + Hash, S: BuildHasher + Default
[src]

fn from_iter<T: IntoIterator<Item=(K, V)>>(iter: T) -> HashMap<K, V, S>

Creates a value from an iterator. Read more

impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S> where K: Eq + Hash, S: BuildHasher
[src]

fn extend<T: IntoIterator<Item=(K, V)>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more

impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S> where K: Eq + Hash + Copy, V: Copy, S: BuildHasher
1.4.0
[src]

fn extend<T: IntoIterator<Item=(&'a K, &'a V)>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more

The Option type. See the module level documentation for more.

fn is_some(&self) -> bool

Returns true if the option is a Some value

Examples

fn main() { let x: Option<u32> = Some(2); assert_eq!(x.is_some(), true); let x: Option<u32> = None; assert_eq!(x.is_some(), false); }
let x: Option<u32> = Some(2);
assert_eq!(x.is_some(), true);

let x: Option<u32> = None;
assert_eq!(x.is_some(), false);

fn is_none(&self) -> bool

Returns true if the option is a None value

Examples

fn main() { let x: Option<u32> = Some(2); assert_eq!(x.is_none(), false); let x: Option<u32> = None; assert_eq!(x.is_none(), true); }
let x: Option<u32> = Some(2);
assert_eq!(x.is_none(), false);

let x: Option<u32> = None;
assert_eq!(x.is_none(), true);

fn as_ref(&self) -> Option<&T>

Converts from Option<T> to Option<&T>

Examples

Convert an Option<String> into an Option<usize>, preserving the original. The map method takes the self argument by value, consuming the original, so this technique uses as_ref to first take an Option to a reference to the value inside the original.

fn main() { let num_as_str: Option<String> = Some("10".to_string()); // First, cast `Option<String>` to `Option<&String>` with `as_ref`, // then consume *that* with `map`, leaving `num_as_str` on the stack. let num_as_int: Option<usize> = num_as_str.as_ref().map(|n| n.len()); println!("still can print num_as_str: {:?}", num_as_str); }
let num_as_str: Option<String> = Some("10".to_string());
// First, cast `Option<String>` to `Option<&String>` with `as_ref`,
// then consume *that* with `map`, leaving `num_as_str` on the stack.
let num_as_int: Option<usize> = num_as_str.as_ref().map(|n| n.len());
println!("still can print num_as_str: {:?}", num_as_str);

fn as_mut(&mut self) -> Option<&mut T>

Converts from Option<T> to Option<&mut T>

Examples

fn main() { let mut x = Some(2); match x.as_mut() { Some(v) => *v = 42, None => {}, } assert_eq!(x, Some(42)); }
let mut x = Some(2);
match x.as_mut() {
    Some(v) => *v = 42,
    None => {},
}
assert_eq!(x, Some(42));

fn cloned(self) -> Option<T>

Maps an Option<&T> to an Option<T> by cloning the contents of the option.

fn iter(&self) -> Iter<T>

Returns an iterator over the possibly contained value.

Examples

fn main() { let x = Some(4); assert_eq!(x.iter().next(), Some(&4)); let x: Option<u32> = None; assert_eq!(x.iter().next(), None); }
let x = Some(4);
assert_eq!(x.iter().next(), Some(&4));

let x: Option<u32> = None;
assert_eq!(x.iter().next(), None);

fn iter_mut(&mut self) -> IterMut<T>

Returns a mutable iterator over the possibly contained value.

Examples

fn main() { let mut x = Some(4); match x.iter_mut().next() { Some(v) => *v = 42, None => {}, } assert_eq!(x, Some(42)); let mut x: Option<u32> = None; assert_eq!(x.iter_mut().next(), None); }
let mut x = Some(4);
match x.iter_mut().next() {
    Some(v) => *v = 42,
    None => {},
}
assert_eq!(x, Some(42));

let mut x: Option<u32> = None;
assert_eq!(x.iter_mut().next(), None);

fn unwrap(self) -> T

Moves the value v out of the Option<T> if it is Some(v).

Panics

Panics if the self value equals None.

Safety note

In general, because this function may panic, its use is discouraged. Instead, prefer to use pattern matching and handle the None case explicitly.

Examples

fn main() { let x = Some("air"); assert_eq!(x.unwrap(), "air"); }
let x = Some("air");
assert_eq!(x.unwrap(), "air");
fn main() { let x: Option<&str> = None; assert_eq!(x.unwrap(), "air"); // fails }
let x: Option<&str> = None;
assert_eq!(x.unwrap(), "air"); // fails

fn expect(self, msg: &str) -> T

Unwraps an option, yielding the content of a Some.

Panics

Panics if the value is a None with a custom panic message provided by msg.

Examples

fn main() { let x = Some("value"); assert_eq!(x.expect("the world is ending"), "value"); }
let x = Some("value");
assert_eq!(x.expect("the world is ending"), "value");
fn main() { let x: Option<&str> = None; x.expect("the world is ending"); // panics with `the world is ending` }
let x: Option<&str> = None;
x.expect("the world is ending"); // panics with `the world is ending`

fn unwrap_or(self, def: T) -> T

Returns the contained value or a default.

Examples

fn main() { assert_eq!(Some("car").unwrap_or("bike"), "car"); assert_eq!(None.unwrap_or("bike"), "bike"); }
assert_eq!(Some("car").unwrap_or("bike"), "car");
assert_eq!(None.unwrap_or("bike"), "bike");

fn unwrap_or_default(self) -> T

Returns the contained value or a default

Consumes the self argument then, if Some, returns the contained value, otherwise if None, returns the default value for that type.

Examples

Convert a string to an integer, turning poorly-formed strings into 0 (the default value for integers). parse converts a string to any other type that implements FromStr, returning None on error.

fn main() { let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().ok().unwrap_or_default(); let bad_year = bad_year_from_input.parse().ok().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); }
let good_year_from_input = "1909";
let bad_year_from_input = "190blarg";
let good_year = good_year_from_input.parse().ok().unwrap_or_default();
let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();

assert_eq!(1909, good_year);
assert_eq!(0, bad_year);

fn unwrap_or_else<F>(self, f: F) -> T where F: FnOnce() -> T

Returns the contained value or computes it from a closure.

Examples

fn main() { let k = 10; assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); assert_eq!(None.unwrap_or_else(|| 2 * k), 20); }
let k = 10;
assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
assert_eq!(None.unwrap_or_else(|| 2 * k), 20);

fn take(&mut self) -> Option<T>

Takes the value out of the option, leaving a None in its place.

Examples

fn main() { let mut x = Some(2); x.take(); assert_eq!(x, None); let mut x: Option<u32> = None; x.take(); assert_eq!(x, None); }
let mut x = Some(2);
x.take();
assert_eq!(x, None);

let mut x: Option<u32> = None;
x.take();
assert_eq!(x, None);

fn map<U, F>(self, f: F) -> Option<U> where F: FnOnce(T) -> U

Maps an Option<T> to Option<U> by applying a function to a contained value

Examples

Convert an Option<String> into an Option<usize>, consuming the original:

fn main() { let maybe_some_string = Some(String::from("Hello, World!")); // `Option::map` takes self *by value*, consuming `maybe_some_string` let maybe_some_len = maybe_some_string.map(|s| s.len()); assert_eq!(maybe_some_len, Some(13)); }
let maybe_some_string = Some(String::from("Hello, World!"));
// `Option::map` takes self *by value*, consuming `maybe_some_string`
let maybe_some_len = maybe_some_string.map(|s| s.len());

assert_eq!(maybe_some_len, Some(13));

fn map_or<U, F>(self, default: U, f: F) -> U where F: FnOnce(T) -> U

Applies a function to the contained value (if any), or returns a default (if not).

Examples

fn main() { let x = Some("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Option<&str> = None; assert_eq!(x.map_or(42, |v| v.len()), 42); }
let x = Some("foo");
assert_eq!(x.map_or(42, |v| v.len()), 3);

let x: Option<&str> = None;
assert_eq!(x.map_or(42, |v| v.len()), 42);

fn map_or_else<U, D, F>(self, default: D, f: F) -> U where D: FnOnce() -> U, F: FnOnce(T) -> U

Applies a function to the contained value (if any), or computes a default (if not).

Examples

fn main() { let k = 21; let x = Some("foo"); assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); let x: Option<&str> = None; assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); }
let k = 21;

let x = Some("foo");
assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);

let x: Option<&str> = None;
assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);

fn ok_or<E>(self, err: E) -> Result<T, E>

Transforms the Option<T> into a Result<T, E>, mapping Some(v) to Ok(v) and None to Err(err).

Examples

fn main() { let x = Some("foo"); assert_eq!(x.ok_or(0), Ok("foo")); let x: Option<&str> = None; assert_eq!(x.ok_or(0), Err(0)); }
let x = Some("foo");
assert_eq!(x.ok_or(0), Ok("foo"));

let x: Option<&str> = None;
assert_eq!(x.ok_or(0), Err(0));

fn ok_or_else<E, F>(self, err: F) -> Result<T, E> where F: FnOnce() -> E

Transforms the Option<T> into a Result<T, E>, mapping Some(v) to Ok(v) and None to Err(err()).

Examples

fn main() { let x = Some("foo"); assert_eq!(x.ok_or_else(|| 0), Ok("foo")); let x: Option<&str> = None; assert_eq!(x.ok_or_else(|| 0), Err(0)); }
let x = Some("foo");
assert_eq!(x.ok_or_else(|| 0), Ok("foo"));

let x: Option<&str> = None;
assert_eq!(x.ok_or_else(|| 0), Err(0));

fn and<U>(self, optb: Option<U>) -> Option<U>

Returns None if the option is None, otherwise returns optb.

Examples

fn main() { let x = Some(2); let y: Option<&str> = None; assert_eq!(x.and(y), None); let x: Option<u32> = None; let y = Some("foo"); assert_eq!(x.and(y), None); let x = Some(2); let y = Some("foo"); assert_eq!(x.and(y), Some("foo")); let x: Option<u32> = None; let y: Option<&str> = None; assert_eq!(x.and(y), None); }
let x = Some(2);
let y: Option<&str> = None;
assert_eq!(x.and(y), None);

let x: Option<u32> = None;
let y = Some("foo");
assert_eq!(x.and(y), None);

let x = Some(2);
let y = Some("foo");
assert_eq!(x.and(y), Some("foo"));

let x: Option<u32> = None;
let y: Option<&str> = None;
assert_eq!(x.and(y), None);

fn and_then<U, F>(self, f: F) -> Option<U> where F: FnOnce(T) -> Option<U>

Returns None if the option is None, otherwise calls f with the wrapped value and returns the result.

Some languages call this operation flatmap.

Examples

fn main() { fn sq(x: u32) -> Option<u32> { Some(x * x) } fn nope(_: u32) -> Option<u32> { None } assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16)); assert_eq!(Some(2).and_then(sq).and_then(nope), None); assert_eq!(Some(2).and_then(nope).and_then(sq), None); assert_eq!(None.and_then(sq).and_then(sq), None); }
fn sq(x: u32) -> Option<u32> { Some(x * x) }
fn nope(_: u32) -> Option<u32> { None }

assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
assert_eq!(Some(2).and_then(sq).and_then(nope), None);
assert_eq!(Some(2).and_then(nope).and_then(sq), None);
assert_eq!(None.and_then(sq).and_then(sq), None);

fn or(self, optb: Option<T>) -> Option<T>

Returns the option if it contains a value, otherwise returns optb.

Examples

fn main() { let x = Some(2); let y = None; assert_eq!(x.or(y), Some(2)); let x = None; let y = Some(100); assert_eq!(x.or(y), Some(100)); let x = Some(2); let y = Some(100); assert_eq!(x.or(y), Some(2)); let x: Option<u32> = None; let y = None; assert_eq!(x.or(y), None); }
let x = Some(2);
let y = None;
assert_eq!(x.or(y), Some(2));

let x = None;
let y = Some(100);
assert_eq!(x.or(y), Some(100));

let x = Some(2);
let y = Some(100);
assert_eq!(x.or(y), Some(2));

let x: Option<u32> = None;
let y = None;
assert_eq!(x.or(y), None);

fn or_else<F>(self, f: F) -> Option<T> where F: FnOnce() -> Option<T>

Returns the option if it contains a value, otherwise calls f and returns the result.

Examples

fn main() { fn nobody() -> Option<&'static str> { None } fn vikings() -> Option<&'static str> { Some("vikings") } assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians")); assert_eq!(None.or_else(vikings), Some("vikings")); assert_eq!(None.or_else(nobody), None); }
fn nobody() -> Option<&'static str> { None }
fn vikings() -> Option<&'static str> { Some("vikings") }

assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
assert_eq!(None.or_else(vikings), Some("vikings"));
assert_eq!(None.or_else(nobody), None);

impl<T> Hash for Option<T> where T: Hash

fn hash<__HT>(&self, __arg_0: &mut __HT) where __HT: Hasher

Feeds this value into the state given, updating the hasher as necessary.

fn hash_slice<H>(data: &[Self], state: &mut H) where H: Hasher
1.3.0

Feeds a slice of this type into the state provided.

impl<T> Debug for Option<T> where T: Debug

fn fmt(&self, __arg_0: &mut Formatter) -> Result<()Error>

Formats the value using the given formatter.

impl<T> Ord for Option<T> where T: Ord

fn cmp(&self, __arg_0: &Option<T>) -> Ordering

This method returns an Ordering between self and other. Read more

impl<T> PartialOrd<Option<T>> for Option<T> where T: PartialOrd<T>

fn partial_cmp(&self, __arg_0: &Option<T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more

fn lt(&self, __arg_0: &Option<T>) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more

fn le(&self, __arg_0: &Option<T>) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

fn gt(&self, __arg_0: &Option<T>) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more

fn ge(&self, __arg_0: &Option<T>) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

impl<T> PartialEq<Option<T>> for Option<T> where T: PartialEq<T>

fn eq(&self, __arg_0: &Option<T>) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, __arg_0: &Option<T>) -> bool

This method tests for !=.

impl<T> Clone for Option<T> where T: Clone

fn clone(&self) -> Option<T>

Returns a copy of the value. Read more

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

impl<T> Default for Option<T>

fn default() -> Option<T>

Returns the "default value" for a type. Read more

impl<T> IntoIterator for Option<T>

type Item = T

The type of the elements being iterated over.

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?

fn into_iter(self) -> IntoIter<T>

Returns a consuming iterator over the possibly contained value.

Examples

fn main() { let x = Some("string"); let v: Vec<&str> = x.into_iter().collect(); assert_eq!(v, ["string"]); let x = None; let v: Vec<&str> = x.into_iter().collect(); assert!(v.is_empty()); }
let x = Some("string");
let v: Vec<&str> = x.into_iter().collect();
assert_eq!(v, ["string"]);

let x = None;
let v: Vec<&str> = x.into_iter().collect();
assert!(v.is_empty());

impl<'a, T> IntoIterator for &'a Option<T>
1.4.0

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?

fn into_iter(self) -> Iter<'a, T>

Creates an iterator from a value. Read more

impl<'a, T> IntoIterator for &'a mut Option<T>
1.4.0

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?

fn into_iter(self) -> IterMut<'a, T>

Creates an iterator from a value. Read more

impl<A, V> FromIterator<Option<A>> for Option<V> where V: FromIterator<A>

fn from_iter<I>(iter: I) -> Option<V> where I: IntoIterator<Item=Option<A>>

Takes each element in the Iterator: if it is None, no further elements are taken, and the None is returned. Should no None occur, a container with the values of each Option is returned.

Here is an example which increments every integer in a vector, checking for overflow:

fn main() { use std::u16; let v = vec!(1, 2); let res: Option<Vec<u16>> = v.iter().map(|&x: &u16| if x == u16::MAX { None } else { Some(x + 1) } ).collect(); assert!(res == Some(vec!(2, 3))); }
use std::u16;

let v = vec!(1, 2);
let res: Option<Vec<u16>> = v.iter().map(|&x: &u16|
    if x == u16::MAX { None }
    else { Some(x + 1) }
).collect();
assert!(res == Some(vec!(2, 3)));

Trait std::hash::Hash1.0.0 [] [src]

pub trait Hash {
    fn hash<H>(&self, state: &mut H) where H: Hasher;

    fn hash_slice<H>(data: &[Self], state: &mut H) where H: Hasher { ... }
}

A hashable type.

The H type parameter is an abstract hash state that is used by the Hash to compute the hash.

If you are also implementing Eq, there is an additional property that is important:

k1 == k2 -> hash(k1) == hash(k2)

In other words, if two keys are equal, their hashes should also be equal. HashMap and HashSet both rely on this behavior.

Derivable

This trait can be used with #[derive] if all fields implement Hash. When derived, the resulting hash will be the combination of the values from calling .hash() on each field.

How can I implement Hash?

If you need more control over how a value is hashed, you need to implement the Hash trait:

fn main() { use std::hash::{Hash, Hasher}; struct Person { id: u32, name: String, phone: u64, } impl Hash for Person { fn hash<H: Hasher>(&self, state: &mut H) { self.id.hash(state); self.phone.hash(state); } } }
use std::hash::{Hash, Hasher};

struct Person {
    id: u32,
    name: String,
    phone: u64,
}

impl Hash for Person {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
        self.phone.hash(state);
    }
}

Required Methods

fn hash<H>(&self, state: &mut H) where H: Hasher

Feeds this value into the state given, updating the hasher as necessary.

Provided Methods

fn hash_slice<H>(data: &[Self], state: &mut H) where H: Hasher
1.3.0

Feeds a slice of this type into the state provided.

Implementors

  • impl<T> Hash for Wrapping<T> where T: Hash
  • impl<T> Hash for NonZero<T> where T: Zeroable + Hash
  • impl<Ret> Hash for fn() -> Ret
  • impl<Ret> Hash for extern fn() -> Ret
  • impl<Ret> Hash for unsafe fn() -> Ret
  • impl<Ret> Hash for unsafe extern fn() -> Ret
  • impl<Ret, A> Hash for fn(A) -> Ret
  • impl<Ret, A> Hash for extern fn(A) -> Ret
  • impl<Ret, A> Hash for unsafe fn(A) -> Ret
  • impl<Ret, A> Hash for unsafe extern fn(A) -> Ret
  • impl<Ret, A, B> Hash for fn(A, B) -> Ret
  • impl<Ret, A, B> Hash for extern fn(A, B) -> Ret
  • impl<Ret, A, B> Hash for unsafe fn(A, B) -> Ret
  • impl<Ret, A, B> Hash for unsafe extern fn(A, B) -> Ret
  • impl<Ret, A, B, C> Hash for fn(A, B, C) -> Ret
  • impl<Ret, A, B, C> Hash for extern fn(A, B, C) -> Ret
  • impl<Ret, A, B, C> Hash for unsafe fn(A, B, C) -> Ret
  • impl<Ret, A, B, C> Hash for unsafe extern fn(A, B, C) -> Ret
  • impl<Ret, A, B, C, D> Hash for fn(A, B, C, D) -> Ret
  • impl<Ret, A, B, C, D> Hash for extern fn(A, B, C, D) -> Ret
  • impl<Ret, A, B, C, D> Hash for unsafe fn(A, B, C, D) -> Ret
  • impl<Ret, A, B, C, D> Hash for unsafe extern fn(A, B, C, D) -> Ret
  • impl<Ret, A, B, C, D, E> Hash for fn(A, B, C, D, E) -> Ret
  • impl<Ret, A, B, C, D, E> Hash for extern fn(A, B, C, D, E) -> Ret
  • impl<Ret, A, B, C, D, E> Hash for unsafe fn(A, B, C, D, E) -> Ret
  • impl<Ret, A, B, C, D, E> Hash for unsafe extern fn(A, B, C, D, E) -> Ret
  • impl<Ret, A, B, C, D, E, F> Hash for fn(A, B, C, D, E, F) -> Ret
  • impl<Ret, A, B, C, D, E, F> Hash for extern fn(A, B, C, D, E, F) -> Ret
  • impl<Ret, A, B, C, D, E, F> Hash for unsafe fn(A, B, C, D, E, F) -> Ret
  • impl<Ret, A, B, C, D, E, F> Hash for unsafe extern fn(A, B, C, D, E, F) -> Ret
  • impl<Ret, A, B, C, D, E, F, G> Hash for fn(A, B, C, D, E, F, G) -> Ret
  • impl<Ret, A, B, C, D, E, F, G> Hash for extern fn(A, B, C, D, E, F, G) -> Ret
  • impl<Ret, A, B, C, D, E, F, G> Hash for unsafe fn(A, B, C, D, E, F, G) -> Ret
  • impl<Ret, A, B, C, D, E, F, G> Hash for unsafe extern fn(A, B, C, D, E, F, G) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H> Hash for fn(A, B, C, D, E, F, G, H) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H> Hash for extern fn(A, B, C, D, E, F, G, H) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H> Hash for unsafe fn(A, B, C, D, E, F, G, H) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H> Hash for unsafe extern fn(A, B, C, D, E, F, G, H) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I> Hash for fn(A, B, C, D, E, F, G, H, I) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I> Hash for extern fn(A, B, C, D, E, F, G, H, I) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I> Hash for unsafe fn(A, B, C, D, E, F, G, H, I) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I> Hash for unsafe extern fn(A, B, C, D, E, F, G, H, I) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J> Hash for fn(A, B, C, D, E, F, G, H, I, J) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J> Hash for extern fn(A, B, C, D, E, F, G, H, I, J) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J> Hash for unsafe fn(A, B, C, D, E, F, G, H, I, J) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J> Hash for unsafe extern fn(A, B, C, D, E, F, G, H, I, J) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K> Hash for fn(A, B, C, D, E, F, G, H, I, J, K) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K> Hash for extern fn(A, B, C, D, E, F, G, H, I, J, K) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K> Hash for unsafe fn(A, B, C, D, E, F, G, H, I, J, K) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K> Hash for unsafe extern fn(A, B, C, D, E, F, G, H, I, J, K) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K, L> Hash for fn(A, B, C, D, E, F, G, H, I, J, K, L) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K, L> Hash for extern fn(A, B, C, D, E, F, G, H, I, J, K, L) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K, L> Hash for unsafe fn(A, B, C, D, E, F, G, H, I, J, K, L) -> Ret
  • impl<Ret, A, B, C, D, E, F, G, H, I, J, K, L> Hash for unsafe extern fn(A, B, C, D, E, F, G, H, I, J, K, L) -> Ret
  • impl<T> Hash for PhantomData<T> where T: ?Sized
  • impl Hash for RangeFull
  • impl<Idx> Hash for Range<Idx> where Idx: Hash
  • impl<Idx> Hash for RangeFrom<Idx> where Idx: Hash
  • impl<Idx> Hash for RangeTo<Idx> where Idx: Hash
  • impl<Idx> Hash for RangeInclusive<Idx> where Idx: Hash
  • impl<Idx> Hash for RangeToInclusive<Idx> where Idx: Hash
  • impl Hash for Ordering
  • impl Hash for TypeId
  • impl<T> Hash for [T; 0] where T: Hash
  • impl<T> Hash for [T; 1] where T: Hash
  • impl<T> Hash for [T; 2] where T: Hash
  • impl<T> Hash for [T; 3] where T: Hash
  • impl<T> Hash for [T; 4] where T: Hash
  • impl<T> Hash for [T; 5] where T: Hash
  • impl<T> Hash for [T; 6] where T: Hash
  • impl<T> Hash for [T; 7] where T: Hash
  • impl<T> Hash for [T; 8] where T: Hash
  • impl<T> Hash for [T; 9] where T: Hash
  • impl<T> Hash for [T; 10] where T: Hash
  • impl<T> Hash for [T; 11] where T: Hash
  • impl<T> Hash for [T; 12] where T: Hash
  • impl<T> Hash for [T; 13] where T: Hash
  • impl<T> Hash for [T; 14] where T: Hash
  • impl<T> Hash for [T; 15] where T: Hash
  • impl<T> Hash for [T; 16] where T: Hash
  • impl<T> Hash for [T; 17] where T: Hash
  • impl<T> Hash for [T; 18] where T: Hash
  • impl<T> Hash for [T; 19] where T: Hash
  • impl<T> Hash for [T; 20] where T: Hash
  • impl<T> Hash for [T; 21] where T: Hash
  • impl<T> Hash for [T; 22] where T: Hash
  • impl<T> Hash for [T; 23] where T: Hash
  • impl<T> Hash for [T; 24] where T: Hash
  • impl<T> Hash for [T; 25] where T: Hash
  • impl<T> Hash for [T; 26] where T: Hash
  • impl<T> Hash for [T; 27] where T: Hash
  • impl<T> Hash for [T; 28] where T: Hash
  • impl<T> Hash for [T; 29] where T: Hash
  • impl<T> Hash for [T; 30] where T: Hash
  • impl<T> Hash for [T; 31] where T: Hash
  • impl<T> Hash for [T; 32] where T: Hash
  • impl<T> Hash for Option<T> where T: Hash
  • impl<T, E> Hash for Result<T, E> where E: Hash, T: Hash
  • impl Hash for u8
  • impl Hash for u16
  • impl Hash for u32
  • impl Hash for u64
  • impl Hash for usize
  • impl Hash for i8
  • impl Hash for i16
  • impl Hash for i32
  • impl Hash for i64
  • impl Hash for isize
  • impl Hash for bool
  • impl Hash for char
  • impl Hash for str
  • impl Hash for ()
  • impl<A> Hash for (A,) where A: Hash
  • impl<A, B> Hash for (A, B) where A: Hash, B: Hash
  • impl<A, B, C> Hash for (A, B, C) where A: Hash, B: Hash, C: Hash
  • impl<A, B, C, D> Hash for (A, B, C, D) where A: Hash, B: Hash, C: Hash, D: Hash
  • impl<A, B, C, D, E> Hash for (A, B, C, D, E) where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash
  • impl<A, B, C, D, E, F> Hash for (A, B, C, D, E, F) where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash
  • impl<A, B, C, D, E, F, G> Hash for (A, B, C, D, E, F, G) where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash
  • impl<A, B, C, D, E, F, G, H> Hash for (A, B, C, D, E, F, G, H) where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H: Hash
  • impl<A, B, C, D, E, F, G, H, I> Hash for (A, B, C, D, E, F, G, H, I) where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H: Hash, I: Hash
  • impl<A, B, C, D, E, F, G, H, I, J> Hash for (A, B, C, D, E, F, G, H, I, J) where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H: Hash, I: Hash, J: Hash
  • impl<A, B, C, D, E, F, G, H, I, J, K> Hash for (A, B, C, D, E, F, G, H, I, J, K) where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H: Hash, I: Hash, J: Hash, K: Hash
  • impl<A, B, C, D, E, F, G, H, I, J, K, L> Hash for (A, B, C, D, E, F, G, H, I, J, K, L) where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H: Hash, I: Hash, J: Hash, K: Hash, L: Hash
  • impl<T> Hash for [T] where T: Hash
  • impl<'a, T> Hash for &'a T where T: Hash + ?Sized
  • impl<'a, T> Hash for &'a mut T where T: Hash + ?Sized
  • impl<T> Hash for *const T
  • impl<T> Hash for *mut T
  • impl Hash for Error
  • impl<T> Hash for Box<T> where T: Hash + ?Sized
  • impl<T> Hash for Arc<T> where T: Hash + ?Sized
  • impl<T> Hash for Rc<T> where T: Hash + ?Sized
  • impl<K, V> Hash for BTreeMap<K, V> where K: Hash, V: Hash
  • impl<T> Hash for BTreeSet<T> where T: Hash
  • impl<'a, B> Hash for Cow<'a, B> where B: Hash + ToOwned + ?Sized
  • impl<E> Hash for EnumSet<E> where E: Hash
  • impl<A> Hash for LinkedList<A> where A: Hash
  • impl Hash for String
  • impl<T> Hash for Vec<T> where T: Hash
  • impl<A> Hash for VecDeque<A> where A: Hash
  • impl<T> Hash for Bound<T> where T: Hash
  • impl Hash for CString
  • impl Hash for CStr
  • impl Hash for OsString
  • impl Hash for OsStr
  • impl Hash for FileType
  • impl Hash for IpAddr
  • impl Hash for Ipv6MulticastScope
  • impl Hash for Ipv4Addr
  • impl Hash for Ipv6Addr
  • impl Hash for SocketAddr
  • impl Hash for SocketAddrV4
  • impl Hash for SocketAddrV6
  • impl<'a> Hash for Prefix<'a>
  • impl<'a> Hash for PrefixComponent<'a>
  • impl<'a> Hash for Component<'a>
  • impl Hash for PathBuf
  • impl Hash for Path
  • impl Hash for Duration

Trait std::fmt::Debug1.0.0 [] [src]

pub trait Debug {
    fn fmt(&self, &mut Formatter) -> Result<()Error>;
}

Format trait for the ? character.

Debug should format the output in a programmer-facing, debugging context.

Generally speaking, you should just derive a Debug implementation.

When used with the alternate format specifier #?, the output is pretty-printed.

For more information on formatters, see the module-level documentation.

This trait can be used with #[derive] if all fields implement Debug. When derived for structs, it will use the name of the struct, then {, then a comma-separated list of each field's name and Debug value, then }. For enums, it will use the name of the variant and, if applicable, (, then the Debug values of the fields, then ).

Examples

Deriving an implementation:

fn main() { #[derive(Debug)] struct Point { x: i32, y: i32, } let origin = Point { x: 0, y: 0 }; println!("The origin is: {:?}", origin); }
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

let origin = Point { x: 0, y: 0 };

println!("The origin is: {:?}", origin);

Manually implementing:

fn main() { use std::fmt; struct Point { x: i32, y: i32, } impl fmt::Debug for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y) } } let origin = Point { x: 0, y: 0 }; println!("The origin is: {:?}", origin); }
use std::fmt;

struct Point {
    x: i32,
    y: i32,
}

impl fmt::Debug for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
    }
}

let origin = Point { x: 0, y: 0 };

println!("The origin is: {:?}", origin);

This outputs:

The origin is: Point { x: 0, y: 0 }

There are a number of debug_* methods on Formatter to help you with manual implementations, such as debug_struct.

Debug implementations using either derive or the debug builder API on Formatter support pretty printing using the alternate flag: {:#?}.

Pretty printing with #?:

fn main() { #[derive(Debug)] struct Point { x: i32, y: i32, } let origin = Point { x: 0, y: 0 }; println!("The origin is: {:#?}", origin); }
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

let origin = Point { x: 0, y: 0 };

println!("The origin is: {:#?}", origin);

This outputs:

The origin is: Point {
    x: 0,
    y: 0
}

Required Methods

fn fmt(&self, &mut Formatter) -> Result<()Error>

Formats the value using the given formatter.

Implementors

Trait std::marker::Copy1.0.0 [] [src]

pub trait Copy: Clone { }

Types that can be copied by simply copying bits (i.e. memcpy).

By default, variable bindings have 'move semantics.' In other words:

fn main() { #[derive(Debug)] struct Foo; let x = Foo; let y = x; // `x` has moved into `y`, and so cannot be used // println!("{:?}", x); // error: use of moved value }
#[derive(Debug)]
struct Foo;

let x = Foo;

let y = x;

// `x` has moved into `y`, and so cannot be used

// println!("{:?}", x); // error: use of moved value

However, if a type implements Copy, it instead has 'copy semantics':

fn main() { // we can just derive a `Copy` implementation #[derive(Debug, Copy, Clone)] struct Foo; let x = Foo; let y = x; // `y` is a copy of `x` println!("{:?}", x); // A-OK! }
// we can just derive a `Copy` implementation
#[derive(Debug, Copy, Clone)]
struct Foo;

let x = Foo;

let y = x;

// `y` is a copy of `x`

println!("{:?}", x); // A-OK!

It's important to note that in these two examples, the only difference is if you are allowed to access x after the assignment: a move is also a bitwise copy under the hood.

When can my type be Copy?

A type can implement Copy if all of its components implement Copy. For example, this struct can be Copy:

fn main() { #[allow(dead_code)] struct Point { x: i32, y: i32, } }
struct Point {
   x: i32,
   y: i32,
}

A struct can be Copy, and i32 is Copy, so therefore, Point is eligible to be Copy.

fn main() { #![allow(dead_code)] struct Point; struct PointList { points: Vec<Point>, } }
struct PointList {
    points: Vec<Point>,
}

The PointList struct cannot implement Copy, because Vec<T> is not Copy. If we attempt to derive a Copy implementation, we'll get an error:

the trait `Copy` may not be implemented for this type; field `points` does not implement `Copy`

When can my type not be Copy?

Some types can't be copied safely. For example, copying &mut T would create an aliased mutable reference, and copying String would result in two attempts to free the same buffer.

Generalizing the latter case, any type implementing Drop can't be Copy, because it's managing some resource besides its own size_of::<T>() bytes.

When should my type be Copy?

Generally speaking, if your type can implement Copy, it should. There's one important thing to consider though: if you think your type may not be able to implement Copy in the future, then it might be prudent to not implement Copy. This is because removing Copy is a breaking change: that second example would fail to compile if we made Foo non-Copy.

Derivable

This trait can be used with #[derive] if all of its components implement Copy and the type implements Clone. The implementation will copy the bytes of each field using memcpy.

How can I implement Copy?

There are two ways to implement Copy on your type:

fn main() { #[derive(Copy, Clone)] struct MyStruct; }
#[derive(Copy, Clone)]
struct MyStruct;

and

fn main() { struct MyStruct; impl Copy for MyStruct {} impl Clone for MyStruct { fn clone(&self) -> MyStruct { *self } } }
struct MyStruct;
impl Copy for MyStruct {}
impl Clone for MyStruct { fn clone(&self) -> MyStruct { *self } }

There is a small difference between the two: the derive strategy will also place a Copy bound on type parameters, which isn't always desired.

Implementors

Trait std::clone::Clone1.0.0 [] [src]

pub trait Clone {
    fn clone(&self) -> Self;

    fn clone_from(&mut self, source: &Self) { ... }
}

A common trait for the ability to explicitly duplicate an object.

Differs from Copy in that Copy is implicit and extremely inexpensive, while Clone is always explicit and may or may not be expensive. In order to enforce these characteristics, Rust does not allow you to reimplement Copy, but you may reimplement Clone and run arbitrary code.

Since Clone is more general than Copy, you can automatically make anything Copy be Clone as well.

Derivable

This trait can be used with #[derive] if all fields are Clone. The derived implementation of clone() calls clone() on each field.

How can I implement Clone?

Types that are Copy should have a trivial implementation of Clone. More formally: if T: Copy, x: T, and y: &T, then let x = y.clone(); is equivalent to let x = *y;. Manual implementations should be careful to uphold this invariant; however, unsafe code must not rely on it to ensure memory safety.

An example is an array holding more than 32 elements of a type that is Clone; the standard library only implements Clone up until arrays of size 32. In this case, the implementation of Clone cannot be derived, but can be implemented as:

fn main() { #[derive(Copy)] struct Stats { frequencies: [i32; 100], } impl Clone for Stats { fn clone(&self) -> Stats { *self } } }
#[derive(Copy)]
struct Stats {
   frequencies: [i32; 100],
}

impl Clone for Stats {
    fn clone(&self) -> Stats { *self }
}

Required Methods

fn clone(&self) -> Self

Returns a copy of the value.

Examples

fn main() { let hello = "Hello"; // &str implements Clone assert_eq!("Hello", hello.clone()); }
let hello = "Hello"; // &str implements Clone

assert_eq!("Hello", hello.clone());

Provided Methods

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source.

a.clone_from(&b) is equivalent to a = b.clone() in functionality, but can be overridden to reuse the resources of a to avoid unnecessary allocations.

Implementors

Trait std::default::Default1.0.0 [] [src]

pub trait Default {
    fn default() -> Self;
}

A trait for giving a type a useful default value.

Sometimes, you want to fall back to some kind of default value, and don't particularly care what it is. This comes up often with structs that define a set of options:

fn main() { #[allow(dead_code)] struct SomeOptions { foo: i32, bar: f32, } }
struct SomeOptions {
    foo: i32,
    bar: f32,
}

How can we define some default values? You can use Default:

#[allow(dead_code)] #[derive(Default)] struct SomeOptions { foo: i32, bar: f32, } fn main() { let options: SomeOptions = Default::default(); }
#[derive(Default)]
struct SomeOptions {
    foo: i32,
    bar: f32,
}


fn main() {
    let options: SomeOptions = Default::default();
}

Now, you get all of the default values. Rust implements Default for various primitives types.

If you want to override a particular option, but still retain the other defaults:

#[allow(dead_code)] #[derive(Default)] struct SomeOptions { foo: i32, bar: f32, } fn main() { let options = SomeOptions { foo: 42, ..Default::default() }; }
fn main() {
    let options = SomeOptions { foo: 42, ..Default::default() };
}

Derivable

This trait can be used with #[derive] if all of the type's fields implement Default. When derived, it will use the default value for each field's type.

How can I implement Default?

Provide an implementation for the default() method that returns the value of your type that should be the default:

fn main() { #![allow(dead_code)] enum Kind { A, B, C, } impl Default for Kind { fn default() -> Kind { Kind::A } } }
enum Kind {
    A,
    B,
    C,
}

impl Default for Kind {
    fn default() -> Kind { Kind::A }
}

Examples

fn main() { #[allow(dead_code)] #[derive(Default)] struct SomeOptions { foo: i32, bar: f32, } }
#[derive(Default)]
struct SomeOptions {
    foo: i32,
    bar: f32,
}

Required Methods

fn default() -> Self

Returns the "default value" for a type.

Default values are often some kind of initial value, identity value, or anything else that may make sense as a default.

Examples

Using built-in default values:

fn main() { let i: i8 = Default::default(); let (x, y): (Option<String>, f64) = Default::default(); let (a, b, (c, d)): (i32, u32, (bool, bool)) = Default::default(); }
let i: i8 = Default::default();
let (x, y): (Option<String>, f64) = Default::default();
let (a, b, (c, d)): (i32, u32, (bool, bool)) = Default::default();

Making your own:

fn main() { #[allow(dead_code)] enum Kind { A, B, C, } impl Default for Kind { fn default() -> Kind { Kind::A } } }
enum Kind {
    A,
    B,
    C,
}

impl Default for Kind {
    fn default() -> Kind { Kind::A }
}

Implementors

Result is a type that represents either success (Ok) or failure (Err).

See the std::result module documentation for details.

fn is_ok(&self) -> bool

Returns true if the result is Ok

Examples

Basic usage:

fn main() { let x: Result<i32, &str> = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result<i32, &str> = Err("Some error message"); assert_eq!(x.is_ok(), false); }
let x: Result<i32, &str> = Ok(-3);
assert_eq!(x.is_ok(), true);

let x: Result<i32, &str> = Err("Some error message");
assert_eq!(x.is_ok(), false);

fn is_err(&self) -> bool

Returns true if the result is Err

Examples

Basic usage:

fn main() { let x: Result<i32, &str> = Ok(-3); assert_eq!(x.is_err(), false); let x: Result<i32, &str> = Err("Some error message"); assert_eq!(x.is_err(), true); }
let x: Result<i32, &str> = Ok(-3);
assert_eq!(x.is_err(), false);

let x: Result<i32, &str> = Err("Some error message");
assert_eq!(x.is_err(), true);

fn as_ref(&self) -> Result<&T, &E>

Converts from Result<T, E> to Result<&T, &E>

Produces a new Result, containing a reference into the original, leaving the original in place.

Examples

Basic usage:

fn main() { let x: Result<u32, &str> = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result<u32, &str> = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); }
let x: Result<u32, &str> = Ok(2);
assert_eq!(x.as_ref(), Ok(&2));

let x: Result<u32, &str> = Err("Error");
assert_eq!(x.as_ref(), Err(&"Error"));

fn as_mut(&mut self) -> Result<&mut T, &mut E>

Converts from Result<T, E> to Result<&mut T, &mut E>

Examples

Basic usage:

fn main() { fn mutate(r: &mut Result<i32, i32>) { match r.as_mut() { Ok(&mut ref mut v) => *v = 42, Err(&mut ref mut e) => *e = 0, } } let mut x: Result<i32, i32> = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result<i32, i32> = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); }
fn mutate(r: &mut Result<i32, i32>) {
    match r.as_mut() {
        Ok(&mut ref mut v) => *v = 42,
        Err(&mut ref mut e) => *e = 0,
    }
}

let mut x: Result<i32, i32> = Ok(2);
mutate(&mut x);
assert_eq!(x.unwrap(), 42);

let mut x: Result<i32, i32> = Err(13);
mutate(&mut x);
assert_eq!(x.unwrap_err(), 0);

fn iter(&self) -> Iter<T>

Returns an iterator over the possibly contained value.

Examples

Basic usage:

fn main() { let x: Result<u32, &str> = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result<u32, &str> = Err("nothing!"); assert_eq!(x.iter().next(), None); }
let x: Result<u32, &str> = Ok(7);
assert_eq!(x.iter().next(), Some(&7));

let x: Result<u32, &str> = Err("nothing!");
assert_eq!(x.iter().next(), None);

fn iter_mut(&mut self) -> IterMut<T>

Returns a mutable iterator over the possibly contained value.

Examples

Basic usage:

fn main() { let mut x: Result<u32, &str> = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result<u32, &str> = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); }
let mut x: Result<u32, &str> = Ok(7);
match x.iter_mut().next() {
    Some(v) => *v = 40,
    None => {},
}
assert_eq!(x, Ok(40));

let mut x: Result<u32, &str> = Err("nothing!");
assert_eq!(x.iter_mut().next(), None);

fn unwrap(self) -> T

Unwraps a result, yielding the content of an Ok.

Panics

Panics if the value is an Err, with a panic message provided by the Err's value.

Examples

Basic usage:

fn main() { let x: Result<u32, &str> = Ok(2); assert_eq!(x.unwrap(), 2); }
let x: Result<u32, &str> = Ok(2);
assert_eq!(x.unwrap(), 2);
fn main() { let x: Result<u32, &str> = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` }
let x: Result<u32, &str> = Err("emergency failure");
x.unwrap(); // panics with `emergency failure`

fn expect(self, msg: &str) -> T
1.4.0

Unwraps a result, yielding the content of an Ok.

Panics

Panics if the value is an Err, with a panic message including the passed message, and the content of the Err.

Examples

Basic usage:

fn main() { let x: Result<u32, &str> = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` }
let x: Result<u32, &str> = Err("emergency failure");
x.expect("Testing expect"); // panics with `Testing expect: emergency failure`

fn unwrap_or(self, optb: T) -> T

Unwraps a result, yielding the content of an Ok. Else it returns optb.

Examples

Basic usage:

fn main() { let optb = 2; let x: Result<u32, &str> = Ok(9); assert_eq!(x.unwrap_or(optb), 9); let x: Result<u32, &str> = Err("error"); assert_eq!(x.unwrap_or(optb), optb); }
let optb = 2;
let x: Result<u32, &str> = Ok(9);
assert_eq!(x.unwrap_or(optb), 9);

let x: Result<u32, &str> = Err("error");
assert_eq!(x.unwrap_or(optb), optb);

fn unwrap_or_else<F>(self, op: F) -> T where F: FnOnce(E) -> T

Unwraps a result, yielding the content of an Ok. If the value is an Err then it calls op with its value.

Examples

Basic usage:

fn main() { fn count(x: &str) -> usize { x.len() } assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); }
fn count(x: &str) -> usize { x.len() }

assert_eq!(Ok(2).unwrap_or_else(count), 2);
assert_eq!(Err("foo").unwrap_or_else(count), 3);

fn unwrap_err(self) -> E

Unwraps a result, yielding the content of an Err.

Panics

Panics if the value is an Ok, with a custom panic message provided by the Ok's value.

Examples

fn main() { let x: Result<u32, &str> = Ok(2); x.unwrap_err(); // panics with `2` }
let x: Result<u32, &str> = Ok(2);
x.unwrap_err(); // panics with `2`
fn main() { let x: Result<u32, &str> = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); }
let x: Result<u32, &str> = Err("emergency failure");
assert_eq!(x.unwrap_err(), "emergency failure");

fn map<U, F>(self, op: F) -> Result<U, E> where F: FnOnce(T) -> U

Maps a Result<T, E> to Result<U, E> by applying a function to a contained Ok value, leaving an Err value untouched.

This function can be used to compose the results of two functions.

Examples

Print the numbers on each line of a string multiplied by two.

fn main() { let line = "1\n2\n3\n4\n"; for num in line.lines() { match num.parse::<i32>().map(|i| i * 2) { Ok(n) => println!("{}", n), Err(..) => {} } } }
let line = "1\n2\n3\n4\n";

for num in line.lines() {
    match num.parse::<i32>().map(|i| i * 2) {
        Ok(n) => println!("{}", n),
        Err(..) => {}
    }
}

fn map_err<F, O>(self, op: O) -> Result<T, F> where O: FnOnce(E) -> F

Maps a Result<T, E> to Result<T, F> by applying a function to a contained Err value, leaving an Ok value untouched.

This function can be used to pass through a successful result while handling an error.

Examples

Basic usage:

fn main() { fn stringify(x: u32) -> String { format!("error code: {}", x) } let x: Result<u32, u32> = Ok(2); assert_eq!(x.map_err(stringify), Ok(2)); let x: Result<u32, u32> = Err(13); assert_eq!(x.map_err(stringify), Err("error code: 13".to_string())); }
fn stringify(x: u32) -> String { format!("error code: {}", x) }

let x: Result<u32, u32> = Ok(2);
assert_eq!(x.map_err(stringify), Ok(2));

let x: Result<u32, u32> = Err(13);
assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));

fn ok(self) -> Option<T>

Converts from Result<T, E> to Option<T>

Converts self into an Option<T>, consuming self, and discarding the error, if any.

Examples

Basic usage:

fn main() { let x: Result<u32, &str> = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result<u32, &str> = Err("Nothing here"); assert_eq!(x.ok(), None); }
let x: Result<u32, &str> = Ok(2);
assert_eq!(x.ok(), Some(2));

let x: Result<u32, &str> = Err("Nothing here");
assert_eq!(x.ok(), None);

fn err(self) -> Option<E>

Converts from Result<T, E> to Option<E>

Converts self into an Option<E>, consuming self, and discarding the success value, if any.

Examples

Basic usage:

fn main() { let x: Result<u32, &str> = Ok(2); assert_eq!(x.err(), None); let x: Result<u32, &str> = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); }
let x: Result<u32, &str> = Ok(2);
assert_eq!(x.err(), None);

let x: Result<u32, &str> = Err("Nothing here");
assert_eq!(x.err(), Some("Nothing here"));

fn and<U>(self, res: Result<U, E>) -> Result<U, E>

Returns res if the result is Ok, otherwise returns the Err value of self.

Examples

Basic usage:

fn main() { let x: Result<u32, &str> = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result<u32, &str> = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result<u32, &str> = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result<u32, &str> = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); }
let x: Result<u32, &str> = Ok(2);
let y: Result<&str, &str> = Err("late error");
assert_eq!(x.and(y), Err("late error"));

let x: Result<u32, &str> = Err("early error");
let y: Result<&str, &str> = Ok("foo");
assert_eq!(x.and(y), Err("early error"));

let x: Result<u32, &str> = Err("not a 2");
let y: Result<&str, &str> = Err("late error");
assert_eq!(x.and(y), Err("not a 2"));

let x: Result<u32, &str> = Ok(2);
let y: Result<&str, &str> = Ok("different result type");
assert_eq!(x.and(y), Ok("different result type"));

fn and_then<U, F>(self, op: F) -> Result<U, E> where F: FnOnce(T) -> Result<U, E>

Calls op if the result is Ok, otherwise returns the Err value of self.

This function can be used for control flow based on result values.

Examples

Basic usage:

fn main() { fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) } fn err(x: u32) -> Result<u32, u32> { Err(x) } assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16)); assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4)); assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2)); assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3)); }
fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
fn err(x: u32) -> Result<u32, u32> { Err(x) }

assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));

fn or<F>(self, res: Result<T, F>) -> Result<T, F>

Returns res if the result is Err, otherwise returns the Ok value of self.

Examples

Basic usage:

fn main() { let x: Result<u32, &str> = Ok(2); let y: Result<u32, &str> = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result<u32, &str> = Err("early error"); let y: Result<u32, &str> = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result<u32, &str> = Err("not a 2"); let y: Result<u32, &str> = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result<u32, &str> = Ok(2); let y: Result<u32, &str> = Ok(100); assert_eq!(x.or(y), Ok(2)); }
let x: Result<u32, &str> = Ok(2);
let y: Result<u32, &str> = Err("late error");
assert_eq!(x.or(y), Ok(2));

let x: Result<u32, &str> = Err("early error");
let y: Result<u32, &str> = Ok(2);
assert_eq!(x.or(y), Ok(2));

let x: Result<u32, &str> = Err("not a 2");
let y: Result<u32, &str> = Err("late error");
assert_eq!(x.or(y), Err("late error"));

let x: Result<u32, &str> = Ok(2);
let y: Result<u32, &str> = Ok(100);
assert_eq!(x.or(y), Ok(2));

fn or_else<F, O>(self, op: O) -> Result<T, F> where O: FnOnce(E) -> Result<T, F>

Calls op if the result is Err, otherwise returns the Ok value of self.

This function can be used for control flow based on result values.

Examples

Basic usage:

fn main() { fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) } fn err(x: u32) -> Result<u32, u32> { Err(x) } assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2)); assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2)); assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9)); assert_eq!(Err(3).or_else(err).or_else(err), Err(3)); }
fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
fn err(x: u32) -> Result<u32, u32> { Err(x) }

assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
assert_eq!(Err(3).or_else(err).or_else(err), Err(3));

impl<T, E> Hash for Result<T, E> where E: Hash, T: Hash

fn hash<__HTE>(&self, __arg_0: &mut __HTE) where __HTE: Hasher

Feeds this value into the state given, updating the hasher as necessary.

fn hash_slice<H>(data: &[Self], state: &mut H) where H: Hasher
1.3.0

Feeds a slice of this type into the state provided.

impl<T, E> Debug for Result<T, E> where E: Debug, T: Debug

fn fmt(&self, __arg_0: &mut Formatter) -> Result<()Error>

Formats the value using the given formatter.

impl<T, E> Ord for Result<T, E> where E: Ord, T: Ord

fn cmp(&self, __arg_0: &Result<T, E>) -> Ordering

This method returns an Ordering between self and other. Read more

impl<T, E> PartialOrd<Result<T, E>> for Result<T, E> where E: PartialOrd<E>, T: PartialOrd<T>

fn partial_cmp(&self, __arg_0: &Result<T, E>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more

fn lt(&self, __arg_0: &Result<T, E>) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more

fn le(&self, __arg_0: &Result<T, E>) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

fn gt(&self, __arg_0: &Result<T, E>) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more

fn ge(&self, __arg_0: &Result<T, E>) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

impl<T, E> PartialEq<Result<T, E>> for Result<T, E> where E: PartialEq<E>, T: PartialEq<T>

fn eq(&self, __arg_0: &Result<T, E>) -> bool

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, __arg_0: &Result<T, E>) -> bool

This method tests for !=.

impl<T, E> Clone for Result<T, E> where E: Clone, T: Clone

fn clone(&self) -> Result<T, E>

Returns a copy of the value. Read more

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

impl<T, E> IntoIterator for Result<T, E>

type Item = T

The type of the elements being iterated over.

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?

fn into_iter(self) -> IntoIter<T>

Returns a consuming iterator over the possibly contained value.

Examples

Basic usage:

fn main() { let x: Result<u32, &str> = Ok(5); let v: Vec<u32> = x.into_iter().collect(); assert_eq!(v, [5]); let x: Result<u32, &str> = Err("nothing!"); let v: Vec<u32> = x.into_iter().collect(); assert_eq!(v, []); }
let x: Result<u32, &str> = Ok(5);
let v: Vec<u32> = x.into_iter().collect();
assert_eq!(v, [5]);

let x: Result<u32, &str> = Err("nothing!");
let v: Vec<u32> = x.into_iter().collect();
assert_eq!(v, []);

impl<'a, T, E> IntoIterator for &'a Result<T, E>
1.4.0

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?

fn into_iter(self) -> Iter<'a, T>

Creates an iterator from a value. Read more

impl<'a, T, E> IntoIterator for &'a mut Result<T, E>
1.4.0

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?

fn into_iter(self) -> IterMut<'a, T>

Creates an iterator from a value. Read more

impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E> where V: FromIterator<A>

fn from_iter<I>(iter: I) -> Result<V, E> where I: IntoIterator<Item=Result<A, E>>

Takes each element in the Iterator: if it is an Err, no further elements are taken, and the Err is returned. Should no Err occur, a container with the values of each Result is returned.

Here is an example which increments every integer in a vector, checking for overflow:

fn main() { use std::u32; let v = vec!(1, 2); let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32| if x == u32::MAX { Err("Overflow!") } else { Ok(x + 1) } ).collect(); assert!(res == Ok(vec!(2, 3))); }
use std::u32;

let v = vec!(1, 2);
let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
    if x == u32::MAX { Err("Overflow!") }
    else { Ok(x + 1) }
).collect();
assert!(res == Ok(vec!(2, 3)));

Trait std::ops::Index1.0.0 [] [src]

pub trait Index<Idx> where Idx: ?Sized {
    type Output: ?Sized;
    fn index(&self, index: Idx) -> &Self::Output;
}

The Index trait is used to specify the functionality of indexing operations like arr[idx] when used in an immutable context.

Examples

A trivial implementation of Index. When Foo[Bar] happens, it ends up calling index, and therefore, main prints Indexing!.

use std::ops::Index; #[derive(Copy, Clone)] struct Foo; struct Bar; impl Index<Bar> for Foo { type Output = Foo; fn index<'a>(&'a self, _index: Bar) -> &'a Foo { println!("Indexing!"); self } } fn main() { Foo[Bar]; }
use std::ops::Index;

#[derive(Copy, Clone)]
struct Foo;
struct Bar;

impl Index<Bar> for Foo {
    type Output = Foo;

    fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
        println!("Indexing!");
        self
    }
}

fn main() {
    Foo[Bar];
}

Associated Types

type Output: ?Sized

The returned type after indexing

Required Methods

fn index(&self, index: Idx) -> &Self::Output

The method for the indexing (Foo[Bar]) operation

Implementors

Trait std::convert::From1.0.0 [] [src]

pub trait From<T> {
    fn from(T) -> Self;
}

Construct Self via a conversion.

Note: this trait must not fail. If the conversion can fail, use TryFrom or a dedicated method which returns an Option<T> or a Result<T, E>.

Examples

String implements From<&str>:

fn main() { let string = "hello".to_string(); let other_string = String::from("hello"); assert_eq!(string, other_string); }
let string = "hello".to_string();
let other_string = String::from("hello");

assert_eq!(string, other_string);

Generic impls

  • From<T> for U implies Into<U> for T
  • from() is reflexive, which means that From<T> for T is implemented

Required Methods

fn from(T) -> Self

Performs the conversion.

Implementors

Trait std::borrow::Borrow1.0.0 [] [src]

pub trait Borrow<Borrowed> where Borrowed: ?Sized {
    fn borrow(&self) -> &Borrowed;
}

A trait for borrowing data.

In general, there may be several ways to "borrow" a piece of data. The typical ways of borrowing a type T are &T (a shared borrow) and &mut T (a mutable borrow). But types like Vec<T> provide additional kinds of borrows: the borrowed slices &[T] and &mut [T].

When writing generic code, it is often desirable to abstract over all ways of borrowing data from a given type. That is the role of the Borrow trait: if T: Borrow<U>, then &U can be borrowed from &T. A given type can be borrowed as multiple different types. In particular, Vec<T>: Borrow<Vec<T>> and Vec<T>: Borrow<[T]>.

If you are implementing Borrow and both Self and Borrowed implement Hash, Eq, and/or Ord, they must produce the same result.

Borrow is very similar to, but different than, AsRef. See the book for more.

Required Methods

fn borrow(&self) -> &Borrowed

Immutably borrows from an owned value.

Examples

fn main() { use std::borrow::Borrow; fn check<T: Borrow<str>>(s: T) { assert_eq!("Hello", s.borrow()); } let s = "Hello".to_string(); check(s); let s = "Hello"; check(s); }
use std::borrow::Borrow;

fn check<T: Borrow<str>>(s: T) {
    assert_eq!("Hello", s.borrow());
}

let s = "Hello".to_string();

check(s);

let s = "Hello";

check(s);

Implementors

Trait std::borrow::BorrowMut1.0.0 [] [src]

pub trait BorrowMut<Borrowed>: Borrow<Borrowed> where Borrowed: ?Sized {
    fn borrow_mut(&mut self) -> &mut Borrowed;
}

A trait for mutably borrowing data.

Similar to Borrow, but for mutable borrows.

Required Methods

fn borrow_mut(&mut self) -> &mut Borrowed

Mutably borrows from an owned value.

Examples

fn main() { use std::borrow::BorrowMut; fn check<T: BorrowMut<[i32]>>(mut v: T) { assert_eq!(&mut [1, 2, 3], v.borrow_mut()); } let v = vec![1, 2, 3]; check(v); }
use std::borrow::BorrowMut;

fn check<T: BorrowMut<[i32]>>(mut v: T) {
    assert_eq!(&mut [1, 2, 3], v.borrow_mut());
}

let v = vec![1, 2, 3];

check(v);

Implementors

Trait std::ops::IndexMut1.0.0 [] [src]

pub trait IndexMut<Idx>: Index<Idx> where Idx: ?Sized {
    fn index_mut(&mut self, index: Idx) -> &mut Self::Output;
}

The IndexMut trait is used to specify the functionality of indexing operations like arr[idx], when used in a mutable context.

Examples

A trivial implementation of IndexMut. When Foo[Bar] happens, it ends up calling index_mut, and therefore, main prints Indexing!.

use std::ops::{Index, IndexMut}; #[derive(Copy, Clone)] struct Foo; struct Bar; impl Index<Bar> for Foo { type Output = Foo; fn index<'a>(&'a self, _index: Bar) -> &'a Foo { self } } impl IndexMut<Bar> for Foo { fn index_mut<'a>(&'a mut self, _index: Bar) -> &'a mut Foo { println!("Indexing!"); self } } fn main() { &mut Foo[Bar]; }
use std::ops::{Index, IndexMut};

#[derive(Copy, Clone)]
struct Foo;
struct Bar;

impl Index<Bar> for Foo {
    type Output = Foo;

    fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
        self
    }
}

impl IndexMut<Bar> for Foo {
    fn index_mut<'a>(&'a mut self, _index: Bar) -> &'a mut Foo {
        println!("Indexing!");
        self
    }
}

fn main() {
    &mut Foo[Bar];
}

Required Methods

fn index_mut(&mut self, index: Idx) -> &mut Self::Output

The method for the indexing (Foo[Bar]) operation

Implementors

Trait std::ops::Deref1.0.0 [] [src]

pub trait Deref {
    type Target: ?Sized;
    fn deref(&self) -> &Self::Target;
}

The Deref trait is used to specify the functionality of dereferencing operations, like *v.

Deref also enables 'Deref coercions'.

Examples

A struct with a single field which is accessible via dereferencing the struct.

use std::ops::Deref; struct DerefExample<T> { value: T } impl<T> Deref for DerefExample<T> { type Target = T; fn deref(&self) -> &T { &self.value } } fn main() { let x = DerefExample { value: 'a' }; assert_eq!('a', *x); }
use std::ops::Deref;

struct DerefExample<T> {
    value: T
}

impl<T> Deref for DerefExample<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.value
    }
}

fn main() {
    let x = DerefExample { value: 'a' };
    assert_eq!('a', *x);
}

Associated Types

type Target: ?Sized

The resulting type after dereferencing

Required Methods

fn deref(&self) -> &Self::Target

The method called to dereference a value

Implementors

Trait std::ops::DerefMut1.0.0 [] [src]

pub trait DerefMut: Deref {
    fn deref_mut(&mut self) -> &mut Self::Target;
}

The DerefMut trait is used to specify the functionality of dereferencing mutably like *v = 1;

DerefMut also enables 'Deref coercions'.

Examples

A struct with a single field which is modifiable via dereferencing the struct.

use std::ops::{Deref, DerefMut}; struct DerefMutExample<T> { value: T } impl<T> Deref for DerefMutExample<T> { type Target = T; fn deref<'a>(&'a self) -> &'a T { &self.value } } impl<T> DerefMut for DerefMutExample<T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { &mut self.value } } fn main() { let mut x = DerefMutExample { value: 'a' }; *x = 'b'; assert_eq!('b', *x); }
use std::ops::{Deref, DerefMut};

struct DerefMutExample<T> {
    value: T
}

impl<T> Deref for DerefMutExample<T> {
    type Target = T;

    fn deref<'a>(&'a self) -> &'a T {
        &self.value
    }
}

impl<T> DerefMut for DerefMutExample<T> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut T {
        &mut self.value
    }
}

fn main() {
    let mut x = DerefMutExample { value: 'a' };
    *x = 'b';
    assert_eq!('b', *x);
}

Required Methods

fn deref_mut(&mut self) -> &mut Self::Target

The method called to mutably dereference a value

Implementors

Trait std::ops::Drop1.0.0 [] [src]

pub trait Drop {
    fn drop(&mut self);
}

The Drop trait is used to run some code when a value goes out of scope. This is sometimes called a 'destructor'.

Examples

A trivial implementation of Drop. The drop method is called when _x goes out of scope, and therefore main prints Dropping!.

struct HasDrop; impl Drop for HasDrop { fn drop(&mut self) { println!("Dropping!"); } } fn main() { let _x = HasDrop; }
struct HasDrop;

impl Drop for HasDrop {
    fn drop(&mut self) {
        println!("Dropping!");
    }
}

fn main() {
    let _x = HasDrop;
}

Required Methods

fn drop(&mut self)

A method called when the value goes out of scope.

When this method has been called, self has not yet been deallocated. If it were, self would be a dangling reference.

After this function is over, the memory of self will be deallocated.

Panics

Given that a panic! will call drop() as it unwinds, any panic! in a drop() implementation will likely abort.

Implementors

Trait std::convert::AsRef1.0.0 [] [src]

pub trait AsRef<T> where T: ?Sized {
    fn as_ref(&self) -> &T;
}

A cheap, reference-to-reference conversion.

AsRef is very similar to, but different than, Borrow. See the book for more.

Note: this trait must not fail. If the conversion can fail, use a dedicated method which returns an Option<T> or a Result<T, E>.

Examples

Both String and &str implement AsRef<str>:

fn main() { 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); }
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);

Generic Impls

  • AsRef auto-dereference if the inner type is a reference or a mutable reference (eg: foo.as_ref() will work the same if foo has type &mut Foo or &&mut Foo)

Required Methods

fn as_ref(&self) -> &T

Performs the conversion.

Implementors

Trait std::convert::AsMut1.0.0 [] [src]

pub trait AsMut<T> where T: ?Sized {
    fn as_mut(&mut self) -> &mut T;
}

A cheap, mutable reference-to-mutable reference conversion.

Note: this trait must not fail. If the conversion can fail, use a dedicated method which returns an Option<T> or a Result<T, E>.

Generic Impls

  • AsMut auto-dereference if the inner type is a reference or a mutable reference (eg: foo.as_ref() will work the same if foo has type &mut Foo or &&mut Foo)

Required Methods

fn as_mut(&mut self) -> &mut T

Performs the conversion.

Implementors

Trait std::iter::Extend1.0.0 [] [src]

pub trait Extend<A> {
    fn extend<T>(&mut self, iter: T) where T: IntoIterator<Item=A>;
}

Extend a collection with the contents of an iterator.

Iterators produce a series of values, and collections can also be thought of as a series of values. The Extend trait bridges this gap, allowing you to extend a collection by including the contents of that iterator.

Examples

Basic usage:

fn main() { // You can extend a String with some chars: let mut message = String::from("The first three letters are: "); message.extend(&['a', 'b', 'c']); assert_eq!("abc", &message[29..32]); }
// You can extend a String with some chars:
let mut message = String::from("The first three letters are: ");

message.extend(&['a', 'b', 'c']);

assert_eq!("abc", &message[29..32]);

Implementing Extend:

fn main() { // A sample collection, that's just a wrapper over Vec<T> #[derive(Debug)] struct MyCollection(Vec<i32>); // Let's give it some methods so we can create one and add things // to it. impl MyCollection { fn new() -> MyCollection { MyCollection(Vec::new()) } fn add(&mut self, elem: i32) { self.0.push(elem); } } // since MyCollection has a list of i32s, we implement Extend for i32 impl Extend<i32> for MyCollection { // This is a bit simpler with the concrete type signature: we can call // extend on anything which can be turned into an Iterator which gives // us i32s. Because we need i32s to put into MyCollection. fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) { // The implementation is very straightforward: loop through the // iterator, and add() each element to ourselves. for elem in iter { self.add(elem); } } } let mut c = MyCollection::new(); c.add(5); c.add(6); c.add(7); // let's extend our collection with three more numbers c.extend(vec![1, 2, 3]); // we've added these elements onto the end assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c)); }
// A sample collection, that's just a wrapper over Vec<T>
#[derive(Debug)]
struct MyCollection(Vec<i32>);

// Let's give it some methods so we can create one and add things
// to it.
impl MyCollection {
    fn new() -> MyCollection {
        MyCollection(Vec::new())
    }

    fn add(&mut self, elem: i32) {
        self.0.push(elem);
    }
}

// since MyCollection has a list of i32s, we implement Extend for i32
impl Extend<i32> for MyCollection {

    // This is a bit simpler with the concrete type signature: we can call
    // extend on anything which can be turned into an Iterator which gives
    // us i32s. Because we need i32s to put into MyCollection.
    fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {

        // The implementation is very straightforward: loop through the
        // iterator, and add() each element to ourselves.
        for elem in iter {
            self.add(elem);
        }
    }
}

let mut c = MyCollection::new();

c.add(5);
c.add(6);
c.add(7);

// let's extend our collection with three more numbers
c.extend(vec![1, 2, 3]);

// we've added these elements onto the end
assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));

Required Methods

fn extend<T>(&mut self, iter: T) where T: IntoIterator<Item=A>

Extends a collection with the contents of an iterator.

As this is the only method for this trait, the trait-level docs contain more details.

Examples

Basic usage:

fn main() { // You can extend a String with some chars: let mut message = String::from("abc"); message.extend(['d', 'e', 'f'].iter()); assert_eq!("abcdef", &message); }
// You can extend a String with some chars:
let mut message = String::from("abc");

message.extend(['d', 'e', 'f'].iter());

assert_eq!("abcdef", &message);

Implementors

X