rust 反序列化元组值生存期问题

z2acfund  于 2022-12-26  发布在  其他
关注(0)|答案(2)|浏览(132)

当我试图反序列化元组中的值时,它不允许我将结果推入数组。

fn main() {
    let raw_value = vec![(1, ("a", "a", 1))];

    //serialise
    let mut serialized_value = vec![];

    for val in raw_value.iter() {
        serialized_value.push((
            bincode::serialize(&val.0).unwrap(),
            bincode::serialize(&val.1).unwrap(),
        ));
    }

    //deserialise
    let mut deserialized_value: Vec<(&str, &str, i32)> = vec![];

    for val in serialized_value {
        deserialized_value.push(bincode::deserialize(&val.1).unwrap());
    }
}

它将发出以下错误:

error[E0597]: `val.1` does not live long enough
  --> src/main.rs:18:54
   |
18 |         deserialized_value.push(bincode::deserialize(&val.1).unwrap());
   |         ---------------------------------------------^^^^^^-----------
   |         |                                            |
   |         |                                            borrowed value does not live long enough
   |         borrow later used here
19 |     }
   |     - `val.1` dropped here while still borrowed

但是如果我重构值使其不在元组中,那么这样做就可以了。
知道为什么吗?

efzxgjgh

efzxgjgh1#

您正在破坏性地迭代serialized_value,因此,在给定的循环迭代结束后,val将被删除,在整个循环结束后,serialized_value将被完全消耗。
如果你改为迭代&serialized_value,那么val将引用容器中的元素,并且serialized_value将在堆栈上保持活动,因为它正在被引用。

4xrmg8kj

4xrmg8kj2#

除了@miszcz2137的回答,下面是工作版本:

fn main() {
    let raw_value = vec![(1, ("a", "a", 1))];

    //serialise
    let mut serialized_value = vec![];

    for val in raw_value.iter() {
        serialized_value.push((
            bincode::serialize(&val.0).unwrap(),
            bincode::serialize(&val.1).unwrap(),
        ));
    }

    //deserialise
    let mut deserialized_value: Vec<(&str, &str, i32)> = vec![];

    for val in &serialized_value {
        deserialized_value.push(bincode::deserialize(&val.1).unwrap());
    }

    println!("{:?}", deserialized_value);
}
[("a", "a", 1)]

也就是说,通过for循环填充向量并不十分习惯,使用迭代器和.collect()是更好的实践:
一个二个一个一个

相关问题