about
04/28/2022
RustBites - DataStr
Rust Bite - DataStr
primitives and aggregates, iterators, String, str, vec, hashmap
1. Primitives and Aggregates
-
Scalar primitives are all Copy types:
Type Example bool, char let b:bool = true; i8, i16, i32, i64, isize let i:i8 = -42; u8, u16, u32, u64, usize let u:u8 = 42; f32, f64 let f:f64 = 3.1415927; -
Aggregate primitives are all Copy types if and only if their elements are Copy:
Type Example array: [T;N], contiguous sequence of T let a:[i32;4] = [1, 2, 3, 4]; assert_eq!(a[1], 2);
a[1] = -2;slice: dynamically sized view into contiguous sequence [T] let s = &a[1..3]; => [2, 3] str: string slice let s = "an str"; -
tuples and structs are Copy if and only if they hold no Move types:
Type Example tuple: finite heterogeneous sequence (T,U,...) let t:(u16, String, f64) = (42, String::from("42"), 3.1415927); assert_eq!(t.0, 42); struct: named fields struct S { a:i8, b:String, c:f64 }
let s = S { a:42, b:String::from("String"), c:3.1415927 }; assert_eq!(s.a, 42);struct: tuple struct T(i8, String, f64)
let t:T = (42, String::from("a string"), 3.1415927); assert_eq!(t.0, 42);struct: unit let s = struct S; s.what().more();
units have no data members, only methods.
2. Iterators:
for item in iter { /* do something with item */ }
for item in iter { /* do something with item */ }
for ch in iter { /* do something with character */ }
m.insert(0, String::from("zero"));
m.insert(1, String::from("one"));
..
let iter = m.iter();
for item in iter { /* do something with item */ }
member function | operation |
---|---|
next(&mut self) -> Option<Self::Item> | Return next element in collection |
count(self) -> usize | Consumes iterator, returning number of iterations |
last(self) -> Option<Self::Item> | Consumes iterator, returning last item |
nth(&mut self, n: usize) -> Option<Self::Item> | Consumes all preceding elements and nth which it returns |
step-by(self, step: usize) ->StepBy<Self> | Creates new iterator starting at same point, but stepping by given amount at each iteration. |
map<B, F>(self, f: F) -> Map<Self, F> | Takes a closure and creates an iterator that calls the closure on each element |
filter<P>(self, predicate: P) - > Filter<Self, P> where P: FnMut(&Self::Item) -> bool |
Creates an iterator which takes a closure to decide if element should be included in result |
skip(self, n: usize) -> Skip<Self> | Creates an iterator that skips the first n elements |
take(self, n:usize) -> Take<Self> | Creates an iterator that returns first n elements |
by_ref(&mut self) -> &mut Self | Supports using these adapters while retaining ownership of the original iterator |
collect<B>(self) -> B | Transforms iterator into collection |
More adapter functions ... | std::iter::Iterator |
Examples: show_coll, show_fold
3. String, str
member function | description |
---|---|
new() -> String | Create new empty String |
from(s: &str) -> String | Creates string from string slice |
as_str(&self) -> &str | Returns string slice |
push_str(&mut self, s: &str) | Appends chars from s |
push(&mut self, ch: char) | Appends ch |
remove(&mut self, n: usize) -> char | Removes char at index n |
insert(&mut self, n: usize, ch: char) | inserts ch at location n |
insert_str(&mut self, n: usize, s: &str) | Inserts contents of s at location n |
len(&self) -> usize |
Returns length of string in bytes, not chars! They are the same only for ASCII characters. |
is_empty(&self) -> bool | Returns true if len() == 0, else false |
clear(&mut self) | Removes all bytes |
from_utf8(vec: Vec<u8> -> REsult<String, FromUtf8Error> | Converts vector of bytes to String. Returns error if invalid UTF-8 |
into_bytes(self) -> Vec<u8> | Convert to Vec of bytes |
as_bytes(&self) -> &[u8] | Returns byte slice |
is_char_boundary(&self, n: usize) -> bool | Is this byte the start of a new UTF-8 character? |
More methods ... | std::string::String |
String Examples:
4. String Formats
5. Vec<T>
member functions | operations |
---|---|
new() -> Vec<T> | Returns a new empty vector. |
push(&mut self, value: T) | Appends value to vector contents |
pop(&mut self) -> Option<T> | Removes last element and returns Some(t:T). If vector is empty returns None. |
insert(&mut self, n: usize, elem: T) | Inserts elem at position n. Panics if out of bounds. |
remove(&mut self, n: usize) -> T | Removes and returns element at position n. Panics if n is out of bounds. |
clear(&mut self) | Removes all elements from vector |
len(&self) -> usize | Returns number of elements in vector |
swap(&mut self, m: usize, n: usize) | Swaps elements at positions m and n. Panics if either m or n are out of bounds. |
as_slice(&self) -> &[T] | Returns slice containing all elements of vector |
as_mut_slice(&mut self) -> &mut [T] | Returns mutable slice with all elements of vector |
Vec Examples:
6. HashMap<K, V>
member functions | operations |
---|---|
new() -> HashMap<K, V> | Returns a new empty hash table. |
insert(&mut self, k: K, v: V) -> Option<V> | Inserts key-value pair into map. If k already existed the old value is replaced by v and returns the old value, otherwise the pair is inserted into the hash table and returns None. |
remove(&mut self, k: &Q) -> Option<V> where K: Borrow<Q>, Q: Hash + Eq |
Removes key from map, returning value if key was in map. If vector is empty returns None. |
clear(&mut self) | Removes all key-value pairs, retains allocated table size |
contains_key<Q: ?Sized>(&self, k: &Q) -> bool | Returns true if map contains k. |
get_key_value<Q: ?Sized>(&mut self, k: &Q) -> Option<(&K, &V)> where K: Borrow<Q>, Q: Hash + Eq |
Returns key-value pair for the supplied key. |
get<Q: ?Sized>(&self, k: &Q) -> Option<&V> | Returns reference to the value for k |
is_empty(&self) -> bool | Returns true if map contains no elements |
iter(&self) -> Iter<K, V> | Returns iterator that visits all elements in arbitrary order |
iter_mut(&mut self) -> IterMut<K, V> | Returns iterator that visits all elements in arbitrary order, returning mutable references. |
keys(&self) -> Keys<K, V> | Returns an iterator visiting all keys in arbitrary order |
values(&self) -> Values<K, V> | Returns an iterator visiting all values in arbitrary order |
values_mut(&mut self) -> ValuesMut<K, V> | Returns an iterator visiting all values mutably in arbitrary order |
More methods ... | HashMap |
Map Examples:
7. Other Collections:
8. Exercises
- Create an array of i32 elements and, using an iterator, display the odd numbers.
-
Create a String instance that contains some UTF-8 characters that are larger
than 1 byte and some that are larger than 2 bytes. Now iterate over the string,
displaying each character and its byte count.
You will probably need to do a little research on UTF-8 to find samples of non-ASCII characters for this exercise.
-
In a Vec of tuples, record your immediate family members and their relationship
to you. Display this collection. Now, convert that to a HashMap and again
display the collection.
Use String formatting to make the displays well organized into fixed-width fields.