Theory and Design of PL (CS 538)
April 06, 2020
chain
: glue two iterators in sequencezip
: pair up two iteratorsstep_by
: iterator skipping every few elementsskip
/take
: skip or take first few elementsmap
/filter
/fold
/scan
let v: Vec<i32> = vec![1, 2, 3];
let v2: Vec<i32> = v.iter() // get iterator
.map(|x| x + 1) // increment each by one
.collect(); // turn back into vector
// same as: let v2: Vec<i32> = v.iter().map(|x| x + 1).collect();
println!("v: {}", v); // OK: .iter() doesn't take ownership
println!("v2: {}", v2);
.foo().bar().baz()
is Rust stylelet v: Vec<i32> = vec![1, 2, 3];
// let v2: Vec<i32> = v.iter().map(|x| x + 1).collect();
let v2iter: Iter<&i32> = v.iter();
let v2map: Map<Iter<&i32>, fn(i32)->i32> = v2iter.map(|x| x + 1);
let v2: Vec<i32> = v2map.collect();
println!("v: {}", v); // OK: .iter() doesn't take ownership
println!("v2: {}", v2);
One or the other: not both!
*ref
returns target of ref
ref.foo()
DerefMut
trait similar for mutable*sp
to *(sp.deref())
*
and deref needed
*
arbitrarily many times until type is Tvar.drop()
struct DropLoudString { data: String }
impl Drop for DropLoudString {
fn drop(&mut self) { println!("Dropping `{}`!", self.data); }
}
fn main() {
let c = DropLoudString { data: String::from("foo") };
{
let d = DropLoudString { data: String::from("bar") };
println!("DropLoudStrings created.");
// Dropping `bar`!
}
// Dropping `foo`!
}
Rc<T>
is type of reference counted pointer to TRc::new(foo)
: make new pointer holding foo
Rc::clone(rc_pt)
: make a copy of rc_pt
clone
when sharingBox<T>
, int count
to_mut