Home
rustbites
Cancel

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]);

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 …

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)
}

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);

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));

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));

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. matches!

Need to check if an expression matches certain pattern?

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

0. Hello, rustbites!

Hello and welcome to rustbites.com

1
2
let hello = "Hello, rustbites!";
println!("{}", hello);