Rust开发小记

  1. 多线程共享trait

    1
    2
    3
    4
    trait 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
    5
    trait 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 //会编译不过
  2. trait中声明async函数

    1
    2
    3
    4
    #[async_trait]
    pub trait T {
    async fn send(&mut self, buf: &[u8]);
    }
  3. 生命周期标注

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    use 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
    14
    use 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)
    }

    会编译不过

  4. tokio::spawn拉起线程,传入的变量使用Arc<Mutex>,clone后传入

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    pub 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();
    //...
    }
    });
    }
  5. Future:https://juejin.cn/post/6844903973950849031