我无法将 json 字符串反序列化为 serde 结构

I can not deserialize json String to struct with serde

我无法将 json 反序列化为结构。

这是模拟我的问题的代码:

use std::sync::mpsc;
use std::sync::mpsc::{Receiver, Sender };

extern crate serde_json;
extern crate serde;
#[macro_use]
extern crate serde_derive;

#[derive(Deserialize, Debug)]
struct Foo<'a> {
    a: u32,
    b: u32,
    c: &'a str,
}

fn main() {

    let (msg_tx, msg_rx): (Sender<Foo>, Receiver<Foo>) = mpsc::channel();
    {
        let js = r#"{"a":33, "b":44, "c": "ss"}"#; // initially I have a json String, here I simulate a problem
        let js_string = String::from(js);
        let f = test(js_string.as_str());

        msg_tx.send(f);
    }
}

fn test(js: &str) -> Foo {
    let foo: Foo = serde_json::from_str(js).unwrap();

    foo
}

运行 该代码导致错误 'js' does not live long enough。 我知道将 Foo c 字段的类型更改为 String 将解决问题,但我想知道是否有其他解决方案。 这个错误的原因是 serde crate 在那种情况下的工作方式,它在返回的 foo 变量内部使用了对原始变量的引用,即 js_string,所以它在调用 [= 之后就超出了范围=14=] 但 f 有一个对它的引用并且比那个范围活得更长。 我仍然是一个生锈的初学者,想掌握生命周期的概念。我试图用函数包装器解决我的问题以设置正确的生命周期,但失败了。

您必须确保 js_string 比频道的寿命更长,为确保这一点,您可以创建一个与频道“合作”的范围:

use std::sync::mpsc;
use std::sync::mpsc::{Receiver, Sender };

extern crate serde_json;
extern crate serde;
#[macro_use]
extern crate serde_derive;

#[derive(Deserialize, Debug)]
struct Foo<'a> {
    a: u32,
    b: u32,
    c: &'a str,
}

fn main() {

    let js = r#"{"a":33, "b":44, "c": "ss"}"#;
    let js_string = String::from(js);
    let f = test(js_string.as_str());
    {
        let (msg_tx, msg_rx): (Sender<Foo>, Receiver<Foo>) = mpsc::channel();
        msg_tx.send(f);
        
    } // channel is dropped here and js_string is no longer borrowed


} // js_string is dropped here

fn test(js: &str) -> Foo {
    let foo: Foo = serde_json::from_str(js).unwrap();
    foo
}