# 回撸Rust China Conf 2020 之《浅谈Rust在算法题和竞赛中的应用》

Review

• 循序渐进的系统性学习（内存管理->类型系统->所有权）
• 主题学习（异步、宏）
• 交流学习（开发者大会、社区）
• 刻意练习（LeetCode）

Speaker: Wu Aoxiang (吴翱翔)

### 1 std::iter::Iterator::peekable

Creates an iterator which can use `[peek](https://doc.rust-lang.org/std/iter/struct.Peekable.html%23method.peek)` to look at the next element of the iterator without consuming it.

`fn peekable(self) -> Peekable<Self>`

``````let xs = [1, 2, 3];
​
let mut iter = xs.iter().peekable();
​
// peek() lets us see into the future
assert_eq!(iter.peek(), Some(&&1));
assert_eq!(iter.next(), Some(&1));

``````

### 2 ?的Option解包能力的应用：LeetCode 7 整数反转。

``````impl Solution {
pub fn reverse(mut x: i32) -> i32 {
|| -> Option<i32> {
let mut ret = 0i32;
while x.abs() != 0 {
x /= 10;
}
Some(ret)
}().unwrap_or(0)
}
}

``````

### 3 std::iter::Iterator::fold的应用：LeetCode 1486 数组异或操作

``````impl Solution {
pub fn xor_operation(n: i32, start: i32) -> i32 {
(1..n).fold(start, |acc, i| { acc ^ start + 2*i as i32 })
}
}

``````

``````use std::net::IpAddr;
​
impl Solution {
pub fn valid_ip_address(ip: String) -> String {
_ => String::from("Neither"),
}
}
}

``````

``````use std::net::IpAddr;
​
impl Solution {
pub fn valid_ip_address(ip: String) -> String {
let array: Vec<Vec<char>> = ip.split('.').map(|x| x.chars().collect()).collect();
for i in 0..array.len() {
if (array[i][0] == '0' && array[i].len() > 1) { return String::from("Neither"); }
}
String::from("IPv4")
},
let array: Vec<Vec<char>> = ip.split(':').map(|x| x.chars().collect()).collect();
for i in 0..array.len() {
if array[i].len() == 0  { return String::from("Neither"); }
}
String::from("IPv6")
},
_ => String::from("Neither"),
}
}
}

``````

### 5 Rust调用C函数

``````extern "C" {
fn rand() -> i32;
}
​
fn main() {
let rand = unsafe { rand() };
println!("{}", rand);
}

``````

### 6 String零开销提供数组访问：std::string::String::into_bytes

This consumes the `String`, so we do not need to copy its contents.

``````#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_bytes(self) -> Vec<u8> {
self.vec
}

``````

### 7 饱和运算（防溢出）

`pub const fn saturating_sub(self, rhs: u8) -> u8`

``````assert_eq!(100u8.saturating_sub(27), 73);
assert_eq!(13u8.saturating_sub(127), 0);

``````

``````#![feature(test)]
extern crate test;
​
pub fn num_identical_pairs(nums: Vec<i32>) -> i32 {
let mut map: [i32;101] = [0;101];
nums.into_iter().fold(0, |mut acc, x| {
acc += map[x as usize];
map[x as usize] += 1;
acc })
}
​
#[cfg(test)]
mod tests {
use test::Bencher;
use super::*;
#[bench]
fn bench_func(b: &mut Bencher) {
b.iter(|| {
num_identical_pairs(vec![1,2,3,1,1,3,1]);
});
}
}

``````

``````PS D:\Project\rust_II\Language\r10_64_benchmark> cargo bench
Finished bench [optimized] target(s) in 0.02s
​
running 1 test
test tests::bench_func ... bench:          81 ns/iter (+/- 74)
​
test result: ok. 0 passed; 0 failed; 0 ignored; 1 measured; 0 filtered out
``````

### 8 善用cargo clippy

`cargo clippy -- -D warnings`