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]);
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 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 …
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)
}
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);
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));
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));
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)
}
Need to check if an expression matches certain pattern?
1
2
let foo = vec!['1','2'];
assert!(matches!(foo.len(), 0..=1));
Hello and welcome to rustbites.com
1
2
let hello = "Hello, rustbites!";
println!("{}", hello);
A new version of content is available.