在RUST中借用和捕获的变量

我正在与paho_mqtt合作,并且我想根据收到的主题发送有关主题的消息。我将代码分为嵌套函数,并使用了变量cli(参见下面的代码)。我认为我需要使用引用来具有有效的代码,但是我仍然不知道如何实现。谢谢您的帮助。

代码:

fn publish_fail_msg(cli: mqtt::AsyncClient,topic: String){
        let msg = mqtt::Message::new(topic,"Fail",QOS[0]);
        cli.publish(msg);
}

fn manage_msgs(cli: mqtt::AsyncClient,msg: mqtt::Message){
        let topic = msg.topic();
        let payload_str = msg.payload_str();

        match topic {
                "main"  => publish_new_topic(cli,payload_str.to_string()),_       => publish_fail_msg(cli,topic.to_string()),}
}

fn main() -> mqtt::AsyncClient {
        // Create the client connection
        let mut cli = mqtt::AsyncClient::new(create_opts).unwrap_or_else(|e| {
                println!("Error creating the client: {:?}",e);
                process::exit(1);
        });

        // Attach a closure to the client to receive callback on incoming messages.
        cli.set_message_callback(|_cli,msg| {
                if let Some(msg) = msg {
                        manage_msgs(cli,msg);
                }
        });

        cli
}

错误:

error[E0507]: cannot move out of captured variable in an `Fnmut` closure
   --> src/main.rs:230:25
    |
212 |     let mut cli = mqtt::AsyncClient::new(create_opts).unwrap_or_else(|e| {
    |         ------- captured outer variable
...
230 |             manage_msgs(cli,msg);
    |                         ^^^ cannot move out of captured variable in an `Fnmut` closure

error[E0505]: cannot move out of `cli` because it is borrowed
   --> src/main.rs:228:30
    |
228 |     cli.set_message_callback(|_cli,msg| {
    |     --- -------------------- ^^^^^^^^^^^ move out of `cli` occurs here
    |     |   |
    |     |   borrow later used by call
    |     borrow of `cli` occurs here
229 |         if let Some(msg) = msg {
230 |             manage_msgs(cli,msg);
    |                         --- move occurs due to use in closure

error[E0382]: borrow of moved value: `cli`
   --> src/main.rs:248:5
    |
212 |     let mut cli = mqtt::AsyncClient::new(create_opts).unwrap_or_else(|e| {
    |         ------- move occurs because `cli` has type `mqtt::AsyncClient`,which does not implement the `Copy` trait
...
228 |     cli.set_message_callback(|_cli,msg| {
    |                              ----------- value moved into closure here
229 |         if let Some(msg) = msg {
230 |             manage_msgs(cli,msg);
    |                         --- variable moved due to use in closure
...
248 |     cli.connect_with_callbacks(conn_opts,on_connect_success,on_connect_failure);
    |     ^^^ value borrowed here after move

chen192 回答:在RUST中借用和捕获的变量

细节在于魔鬼:我找到了问题,即_cli。我将其替换为cli: &mqtt::AsyncClient,然后可以将引用发送给嵌套函数。也许有更好的解决方案,很高兴看到它们。

本文链接:https://www.f2er.com/3164619.html

大家都在问