#010 Feb 2022

10. cloned vs copied

Rust provides built-in methods to copy or clone elements when using an iterator.

Eg.

1
let nums: Vec<u32> = nums1.iter().chain(&nums2).copied().collect();

What’s the difference? and when is it useful?

You may have done something like this:

1
let nums: Vec<u32> = nums1.iter().chain(&nums2).map(|x| *x).collect();

but instead, use copied.

1
let nums: Vec<u32> = nums1.iter().chain(&nums2).copied().collect();

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
let nums = vec![1,2,3,4];
let nums2 = vec![5,6,7,8];

// doiing it manually by copying
// let all_nums: Vec<u32> = nums.iter().chain(&nums2).map(|x| *x).collect();

// doiing it manually by cloneing
// let all_nums: Vec<u32> = nums.iter().chain(&nums2).map(|x| x.clone()).collect();

// but why not just use provided functionality ??!
let all_nums: Vec<u32> = nums.iter().chain(&nums2).copied().collect();

// or cloned if copy it is not an option
//let all_nums: Vec<u32> = nums.iter().chain(&nums2).cloned().collect();

 assert_eq!(all_nums, vec![1,2,3,4,5,6,7,8]);

Difference between cloned and copied?

Same reasoning aplies as for Copy and Clone traits. Use copied to avoid to accidentally cloing iterator elements. Use copied when possible.

#009 Feb 2022

9. Inspecting iterator

Ever wondered how to print while iterating?

Use inspect.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let cars = vec!["Skoda", "Ferrari", "Ford"];

let car_lenghts: Vec<u32> = cars
    .iter()
    .enumerate()
    .inspect(|(idx, s)| println!("{idx} - {s}"))
    .map(|(_, name)| name.len() as u32)
    .collect();

assert!( car_lenghts == vec![5,7,4
#008 Feb 2022

8. Drain

Use drain to remove specified range from a vector.

1
2
3
4
5
let mut a = vec![1,2,3,4,5];

let _ = a.drain(0..3);

assert!(a == vec![4,5]);

What is the difference to call into_iter which returns T ?

into_iter takes the collection by value and consumes it.

drain borrows mutable reference, and returns a drain iterator of elements. If such iterator is dropped without exhausting it, all elements are dropped.

#007 Feb 2022

7. iter() vs into_iter()

What is the difference between .iter() and .into_iter()?

iter yields &T

into_iter may yield any of T, &T or &mut T based on context.

1
2
3
4
5
6
7
8
9
let cars = vec!["Skoda", "Ferrari", "Ford"];

for car in cars.iter() {
    println!("{car}");
}

for car in cars.into_iter() {
    println!("{car}");
}

this works but …

This does not. This results in compile error because cars are moved due to into_iter call.

1
2
3
4
5
6
7
8
9
let cars = vec!["Skoda", "Ferrari", "Ford"];

for car in cars.into_iter() {
  println!("{car}");
}

for car in cars.iter() {
    println!("{car}");
}
#006 Jan 2022

6. non-exhaustive enums

Use non-exhaustive attribute to indicate that enum may have more variants in future.

1
2
3
4
5
#[non_exhaustive]
enum Event{
  Error,
  Completed(String)
}

If such enum is used in match pattern, it is required to handle ’_’ pattern.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let event = Event::Error;
match event {
    Event::Error => {
        println!("error")
    }
    Event::Completed(s) => {
        println!("completed {}", s)
    }
    _ => {
        println!("unknown")
    }
}

How is this useful?

If you are a maintainer of a library and you’d expect to add more variants in the future.

This approach helps you to build a library with non-breaking code changes for library users.

#005 Jan 2022

5. Loop breaks and labels

Breaks and labels in loops?

IT is possible to use a label to specify which enclosing loop is affected.

1
2
3
4
5
6
7
8
let s = 'outer: loop {
      for idx in 0..10 {
          if idx == 4 {
              break 'outer idx;
          }
      }
  };
assert!(s == 4);
#004 Jan 2022

4. Option -> Result

Convert Option to Result easily.

1
2
3
let o: Option<u32> = Some(200u32);
let r: Result<u32,()> = o.ok_or(());
assert_eq!(r, Ok(200u32));
#003 Jan 2022

3. Result -> Option

Convert Result to Option easily.

1
2
3
let r: Result<u32,()> = Ok(200u32);
let o: Option<u32> = r.ok();
assert_eq!(o, Some(200u32));
#002 Jan 2022

2. mysterious @

Use @ to bind a pattern to a name.

1
2
3
4
5
6
let foo = 4;

match foo {
    x @ 0..=5 => assert_eq!(x,4),
    y @ _ => panic!("{}-too many!", y)
}
1
2
3
4
5
6
let point: (u32,u32) = (1, 2);

match point {
    (1, y @ _) => assert_eq!(y,2),
    _ => {}
}
1
2
3
4
5
let point: (u32,u32) = (1, 2);
let mypoint @ (x, _) = point;

assert_eq!(x,1);
assert_eq(mypoint,point);
#001 Jan 2022

1. matches!

Need to check if an expression matches certain pattern?

1
2
let foo = vec!['1','2'];
assert!(matches!(foo.len(), 0..=1));

The example above checks if len is 0 or 1.

Or

1
2
3
let bar = Some(4);

assert!(matches!(bar, Some(x) if x > 2));