在重新广播(redis to zmq)实现中,我无法解决临时值的生存期问题(从循环中使用的pubsub消息派生出来)。
我很理解其中的原因,但到目前为止,我无法生成Vec<&String>,因此需要传递给zmq发布服务器。我尝试了不同的类型,克隆等,但我只是得到了相同或类似的错误有关的所有权和寿命。
有问题的代码:
async fn ps_rebroadcaster() -> Result<(), ApiError>{
let mut inproc_publisher: async_zmq::Publish<std::vec::IntoIter<&std::string::String>, &std::string::String> = async_zmq::publish("ipc://pricing")?.bind()?;
let con_str = &APP_CONFIG.REDIS_URL;
let conn = create_client(con_str.to_string())
.await
.expect("Can't connect to redis");
let mut pubsub = conn.get_async_connection().await?.into_pubsub();
match pubsub.psubscribe("T1050_*").await {
Ok(_) => {}
Err(_) => {}
};
let mut msg_stream = pubsub.into_on_message();
loop {
let result = msg_stream.next().await;
match result {
Some(message) => {
let channel_name = message.get_channel_name().to_string();
let payload_value: redis::Value = message.get_payload().expect("Can't get payload of message");
let payload_string: String = FromRedisValue::from_redis_value(&payload_value).expect("Can't convert from Redis value");
let item: Vec<&String> = vec![&channel_name , &payload_string ];
// problem here ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
inproc_publisher.send(item.into()).await?;
}
None => {
println!("None received");
continue;
}
}
}
}而错误是:
error[E0597]: `channel_name` does not live long enough
--> src/server.rs:248:47
|
248 | let item: Vec<&String> = vec![&channel_name , &payload_string ];
| ^^^^^^^^^^^^^ borrowed value does not live long enough
249 |
250 | inproc_publisher.send(item.into()).await?;
| ---------------------------------- borrow later used here
251 | }
| - `channel_name` dropped here while still borrowed
error[E0597]: `payload_string` does not live long enough
--> src/server.rs:248:63
|
248 | let item: Vec<&String> = vec![&channel_name , &payload_string ];
| ^^^^^^^^^^^^^^^ borrowed value does not live long enough
249 |
250 | inproc_publisher.send(item.into()).await?;
| ---------------------------------- borrow later used here
251 | }
| - `payload_string` dropped here while still borrowed发布于 2022-07-23 04:51:53
这会失败,因为接收器需要一个Into<Message>,但显然没有立即执行转换,因此引用需要继续存在一些未指定的时间,并且它们引用的值过早地被销毁。基本上,你需要给水槽一个拥有的价值而不是借来的价值。
您可以通过将String转换为Message值,然后将它们交给Publish接收器,或者给它一个可以转换为Message的自有值来实现这一点。没有从String到Message的转换,但是有从Vec<u8>的转换,您可以通过使用String::into_bytes()方法将String转换为Vec<u8>而不进行任何复制。
https://stackoverflow.com/questions/73086303
复制相似问题