我当前使用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.我该怎么补救呢?
1条答案
按热度按时间v8wbuo2f1#
Bytes::from
是为&'static [u8]
实现的,而String::as_bytes
没有给予静态引用。必须为Bytes::from
提供一些拥有的数据结构。我选择直接传递text_owned
变量,因为Bytes
实现了From<String>
: