简体   繁体   English

存储结构上的引用并反序列化它们

[英]Storing references on structures and deserializing them

I am parsing a toml config file and retrieve it's content into some structs, using serde and toml .我正在解析一个 toml 配置文件,并使用serdetoml将其内容检索到一些结构中。

So, a config structure could be defined like:因此,配置结构可以定义为:

 #[derive(Deserialize, Debug)] pub struct Config<'a> { #[serde(borrow)] pub server: Inner<'a> }

and another related:和另一个相关的:

 #[derive(Deserialize, Debug)] pub struct Inner<'a> { pub iprop1: &'a str, pub iprop2: &'a str, }

This is the pub interface exposed for loading the config:这是为加载配置而暴露的 pub 接口:

 pub fn load() -> Config<'static> { let config_file: String = fs::read_to_string(CONFIG_FILE_IDENTIFIER).expect("Error opening or reading the configuration file"); toml::from_str(config_file.as_str()).expect("Error generating the configuration") }

So, the issue it's clear.那么,问题就清楚了。 I can return data owned by the load() function.我可以返回load() function 拥有的数据。

I could change all the &str refereneces to String , because I am not able to fully comprehend how to properly play with references in Rust, but I would like to know, if there's another way to validate those references with lifetimes in Rust, so my structs can start to hold references instead owned values. I could change all the &str refereneces to String , because I am not able to fully comprehend how to properly play with references in Rust, but I would like to know, if there's another way to validate those references with lifetimes in Rust, so my structs可以开始保存引用而不是拥有值。

References refer to data owned elsewhere.参考是指在别处拥有的数据。 For this to work, the data being referred to must live at least as long as the reference, otherwise you have a reference to data that no longer exists.为此,被引用的数据必须至少与引用一样长,否则您对不再存在的数据的引用。

In your load() function, the return type declares that Config will borrow data that is 'static .在您的load() function 中,返回类型声明Config将借用'static数据。 This is a special lifetime that refers to data that is valid for the entire lifetime of the program.这是一个特殊的生命周期,它指的是在程序的整个生命周期内都有效的数据。

However, toml::from_str() here borrows from config_file , which does not live for the entire lifetime of the program.但是,这里的toml::from_str()是从config_file借用的,它不会在程序的整个生命周期内都存在。 It lives only until load() returns.它只存在于load()返回。 You are attempting to return a reference to data owned by a function local, which is impossible, because the data will be destroyed before the returned reference can ever be used.您正在尝试返回对 function 本地拥有的数据的引用,这是不可能的,因为在返回的引用可以使用之前数据将被销毁。

If there is nowhere else for config_file to live, the data should indeed be owned by the Config structure.如果config_file无处可存,则数据确实应该归Config结构所有。 The way you express that is by using String instead of &str within that structure.您表达的方式是在该结构中使用String而不是&str

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM