使用serde_json :: from_str反序列化为带有&'静态字符串的结构具有生命周期错误

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (285)

我正在尝试测试我设置用于Dart,JS和Python UI框架的JSON桥。它适用于那些,但是当我尝试使用tui-rs在Rust程序中进行相同的UI /逻辑拆分时,我在尝试反序列化UI线程上的逻辑线程结果时会遇到生命周期错误。

我理解使用JSON进行层间通信都是用Rust编写的,不是理想的做事方式,但鉴于我的目标,我希望这是可以理解的。

我已经尝试过克隆,它可以用于序列化并从UI发送到逻辑但是这对于从逻辑到UI的反序列化不起作用

use std::sync::mpsc;
use std::sync::mpsc::{Receiver, Sender};
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
use serde::{Deserialize, Serialize};

#[macro_export]
macro_rules! BridgeResult {
    ($result:expr, $data:expr) => {
        BridgeResult {
            result: $result,
            data: vec![$data.to_string()],
        }
    };
}

#[derive(Serialize, Deserialize)]
struct BridgeResult {
    result: &'static str,
    data: Vec<String>,
}

#[derive(Serialize, Deserialize)]
struct App {
    state: i64,
}

impl Default for App {
    fn default() -> App {
        App { state: 0 }
    }
}

fn main() {
    let (to_logic, from_ui) = mpsc::channel();
    let (to_ui, from_logic) = mpsc::channel();

    ui(to_logic, from_logic);
    logic(to_ui, from_ui);
}

fn ui(tx: Sender<(String, String)>, rx: Receiver<(String)>) {
    let app = App::default();

    let app_string = serde_json::to_string(&app)
        .expect("failed to encode app struct for sending to logic heard");

    tx.send(("binary_switch".to_string(), app_string))
        .expect("failed to send binary_switch call and data to logic thread");
    let output_string = rx
        .recv()
        .expect("failed to get a result from logic's initialize");
    let output: BridgeResult = serde_json::from_str(&output_string)
        .expect("failed to decode result from logic's binary_switch");

    if output.result != "Ok()" {
        panic!("init failed due to: \n {:?}", output.data);
    } else {
        println!("{:?}", output.data);
    }
}

fn logic(tx: Sender<(String)>, rx: Receiver<(String, String)>) {
    loop {
        let (function, arguments) = rx
            .recv()
            .expect("failed to receive function and arguments from ui thread");
        let result = match function.as_str() {
            "binary_switch" => binary_switch(&arguments),
            _ => {
                BridgeResult! {"Err()", format!("cannot find rust function branch matching {}", function)}
            }
        };

        let output = match serde_json::to_string(&result) {
            Ok(output) => output,
            Err(_) => "{'result' : 'Err()', 'data': 'failed exit encoding!!!'}".to_string(),
        };
        tx.send(output)
            .expect("failed to send the output back to the ui thread");
    }
}

fn binary_switch(data: &String) -> BridgeResult {
    #[derive(Deserialize)]
    struct Arguments {
        state: i64,
    }

    let mut arguments: Arguments = match serde_json::from_str(&data) {
        Ok(data) => data,
        Err(err) => return BridgeResult! {"Err()", format!("failed to parse arguments\n, {}", err)},
    };

    if arguments.state == 0 {
        arguments.state += 1;
    } else {
        arguments.state -= 1;
    }

    BridgeResult! {"Ok()", arguments.state}
}

我希望这能反序列化BridgeResult类型并使用数据字段,其中应包含字符串1。实际上,我得到:

error[E0597]: `output_string` does not live long enough
  --> src/main.rs:55:53
   |
55 |     let output: BridgeResult = serde_json::from_str(&output_string)
   |                                ---------------------^^^^^^^^^^^^^^-
   |                                |                    |
   |                                |                    borrowed value does not live long enough
   |                                argument requires that `output_string` is borrowed for `'static`
...
63 | }
   | - `output_string` dropped here while still borrowed
提问于
用户回答回答于
struct BridgeResult {
    result: &'static str,
    data: Vec<String>,
}

BridgeResult被定义为持有result一个静态字符串。这与将从输入字符串反序列化的内容不兼容。您需要结果是拥有的String或从输入借来的东西。

尝试

struct BridgeResult<'a> {
    result: &'a str,
    data: Vec<String>,
}

扫码关注云+社区

领取腾讯云代金券