Fork me on GitHub

Rust 标准库

1.One-Liners

1.strings

// 1. 拼接字符串
format!("{x}{y}")

// 2.显示Display
write!(x, "{y}")

// 3. 分隔符分开string,s.split(pattern)
s.split("abc");
s.split('/');
s.split(char::is_numeric());
s.slit_whitespace();
s.lines(); // 换行区分
Regex::new(r"\s")?.split("one two three");

2 I/O

// 1.创建文件
File::create(PATH)?

// 也可以
OpenOptions::new().create(true).write(true).truncate(true).optn(PATH)?

3 Macros

macro_rule! var_args {
  ($($args:expr), *) => {{{}}}
}

// 使用args参数,调用f多次
$(f($args);)*

4 Esoterics

// 1.闭包
wants_closure({
  let c = outer.clone;
  move || use_clone(c)
})

// try cloure
iter.try_for_each(|x| { OK::<(), Error>(())})?;


// 如果T是Copy的,迭代和修改&mut [T]
Cell::from_mut(mut_slice).as_slice_of_cells()

// 用长度获取subslice
&original_slice[offset..][..length]

// Canary确保 T 对象安全
const _: Option<&dyn T> = None;

2.线程安全

实现T:Send可以移动到另一个线程,T:Sync可共享

例子 Send* !Send
Sync* Most types ... Arc, Mutex MutexGuard, RwLockReadGuard
!Sync Cell,RefCell Rc, &dyn Trait, *const T, *mut T

3.迭代器

3.1获取迭代器

基本使用
假设有一个c 集合类型为C

  • c.into_iter(),需要C类型实现IntoIterator trait 消耗c
  • c.iter() 借用,不消耗
  • c.iter_mut()可变借用

迭代器

  • i.next() 返回Some(x),c的下一个元素或者None

loops

  • for x in c {} 语法糖调用c.into_iter() 知道None

3.2 实现迭代器

基础,假设struct Collection<T> {}

  • struct IntoIter<T> {}
  • impl Iterator for IntoIter {} 实现Iterator::next()

共享和可变

  • struct Iter<T> {} impl Iterator for Iter<T> {}
  • struct IterMut<T> {} , impl Iterator for IterMut<T> {}

增加方法

Collection::iter(&self) -> Iter
Collection::iter_mut(&mut self) -> IterMut

loops可以工作

  • impl IntoIterator for Collection {} — Now for x in c {} works.
  • impl IntoIterator for &Collection {} — Now for x in &c {} works.
  • impl IntoIterator for &mut Collection {} — Now for x in &mut c {} works.

4.数字转换

↓ Have / Want → u8 … i128 f32 / f64 String
u8 … i128 u8::try_from(x)? x as f32 x.to_string()
f32 / f64 x as u8 x as f32 x.to_string()
String x.parse::()? x.parse::()? x

5.string转换

6.string输出

posted @ 2022-09-03 22:41  BabyMelvin  阅读(300)  评论(0编辑  收藏  举报