rust 为什么传递一个字节给一个函数会导致生存期错误,即使它保证在丢弃之前完成?如何修复?

2admgd59  于 2023-03-02  发布在  其他
关注(0)|答案(1)|浏览(82)

我当前使用bytes板条箱的代码:

pub async fn send_msg(online_users: Arc<Mutex<OnlineUsers>>, msg: &Message, from: &str) -> io::Result<()> {
    let target_user = msg.args.get(0).ok_or(io::Error::from(io::ErrorKind::InvalidInput))?;
    if let Content::Text(ref text) = msg.content {
        let text_owned = text.clone();
        let text_byte = Bytes::from(text_owned.as_bytes());
        let mut online_users = online_users.lock().await;
        online_users.send_to_user(target_user, text_byte).await; 
    }
    Ok(())
}

错误发生在send_to_user()调用处,其定义为:

pub async fn send_to_user(&mut self, name: &str, content: Bytes) -> io::Result<()> {
    let target_user = self
        .list
        .get_mut(name)
        .ok_or(io::Error::new(io::ErrorKind::NotConnected, name.clone()))?;
    target_user.send(content).await?;
    Ok(())
}

错误消息如下:

error[E0597]: `text_owned` does not live long enough
  --> server/src/handler.rs:28:37
   |
28 |         let text_byte = Bytes::from(text_owned.as_bytes());
   |                         ------------^^^^^^^^^^^^^^^^^^^^^-
   |                         |           |
   |                         |           borrowed value does not live long enough
   |                         argument requires that `text_owned` is borrowed for `'static`
...
31 |     }
   |     - `text_owned` dropped here while still borrowed

我不明白为什么它的寿命不够长。因为我在send_to_user()上调用了. wait,所以它必须在send_msg()到达其结尾并删除所有变量之前完成。我希望:
1.解释为什么会这样。
1.我该怎么补救呢?

v8wbuo2f

v8wbuo2f1#

Bytes::from是为&'static [u8]实现的,而String::as_bytes没有给予静态引用。必须为Bytes::from提供一些拥有的数据结构。我选择直接传递text_owned变量,因为Bytes实现了From<String>

pub async fn send_msg(online_users: Arc<Mutex<OnlineUsers>>, msg: &Message, from: &str) -> io::Result<()> {
    let target_user = msg.args.get(0).ok_or(io::Error::from(io::ErrorKind::InvalidInput))?;
    if let Content::Text(ref text) = msg.content {
        let text_owned = text.clone();
        let text_byte = Bytes::from(text_owned);
        let mut online_users = online_users.lock().await;
        online_users.send_to_user(target_user, text_byte).await; 
    }
    Ok(())
}

相关问题