多线程共享trait
1
2
3
4trait T {}
struct B {}
impl T for B {}
let p: Arc<Mutex<Box<dyn T>>> = Arc::new(Mutex::new(Box::new(B{})))需要注意struct类型的对象和trait之间不能互转,比如:
1
2
3
4
5trait T {}
struct B {}
impl T for B {}
let p: Arc<Mutex<Box<B>>> = Arc::new(Mutex::new(Box::new(B{})))
let p_trait: Arc<Mutex<Box<dyn T>>> = p //会编译不过trait中声明async函数
1
2
3
4
pub trait T {
async fn send(&mut self, buf: &[u8]);
}生命周期标注
1
2
3
4
5
6
7
8
9
10
11
12
13use std::fs;
use std::io;
use serde::{Deserialize, Serialize};
pub fn load_data_from_file(cfg_file: String) -> Result<String, io::Error> {
let data = fs::read_to_string(cfg_file)?;
Ok(data)
}
pub fn load_cfg_from_data<'a, C: Deserialize<'a> + Serialize>(data: &'a String) -> Result<C, io::Error> {
let cfg: C = serde_json::from_str::<C>(&data)?;
Ok(cfg)
}data在外部调用load_data_from_file获取,然后调用load_cfg_from_data时传入
如在load_cfg_from_data中读取写做:1
2
3
4
5
6
7
8
9
10
11
12
13
14use std::fs;
use std::io;
use serde::{Deserialize, Serialize};
pub fn load_data_from_file(cfg_file: String) -> Result<String, io::Error> {
let data = fs::read_to_string(cfg_file)?;
Ok(data)
}
pub fn load_cfg_from_data<'a, C: Deserialize<'a> + Serialize>(cfg_file: String) -> Result<C, io::Error> {
let data = load_data_from_file(cfg_file)?;
let cfg: C = serde_json::from_str::<C>(&data)?;
Ok(cfg)
}会编译不过
tokio::spawn拉起线程,传入的变量使用Arc<Mutex
>,clone后传入 1
2
3
4
5
6
7
8
9
10
11
12pub async fn f(_handle: Arc<Mutex<H>>) {
// ...
let _clone_h = _handle.clone();
let _join = tokio::spawn(async move {
loop {
//...
let _clone_handle = _clone_h.clone();
//...
}
});
}
Rust开发小记
- 本文链接: https://qianqians.github.io/2023/07/06/Rust开发小记/
- 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!