其他分享
首页 > 其他分享> > Rust 标准库

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

迭代器

loops

3.2 实现迭代器

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

共享和可变

增加方法

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

loops可以工作

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输出

标签:mut,string,Collection,Rust,标准,iter,impl,split
来源: https://www.cnblogs.com/ellabrain/p/16653887.html