我的lib.rs
中有以下结构pub enum ConfigurationSource {
StringContent(String),
FileContent(PathBuf)
}
pub struct ConfigurationBuilder<'a> {
config: Value,
bundles: HashMap<&'a str, &'a Vec<ConfigurationSource>>
}
impl<'a> ConfigurationBuilder<'a>{
pub fn new(base_source: &ConfigurationSource) -> ConfigurationBuilder{
let base_config: Value = from_str("{}").unwrap();
let mut config_builder = ConfigurationBuilder{
config: base_config,
bundles: HashMap::new()
};
config_builder.merge_source(&base_source);
return config_builder;
}
//more code here
pub fn define_bundle(&mut self, bundle_key: &str, sources: &Vec<ConfigurationSource>){
self.bundles.insert(bundle_key, sources);
}
}
我不希望ConfigurationBuilder实例中的捆绑包Hashmap拥有传递到bundle_key
方法的source
或define_bundle
。
我在构建时遇到以下两个编译错误
error[E0312]: lifetime of reference outlives lifetime of borrowed content...
--> src\lib.rs:67:41
|
67 | self.bundles.insert(bundle_key, sources);
| ^^^^^^^
|
note: ...the reference is valid for the lifetime 'a as defined on the impl at 27:1...
--> src\lib.rs:27:1
|
27 | / impl<'a> ConfigurationBuilder<'a>{
28 | |
29 | | pub fn new(base_source: &ConfigurationSource) -> ConfigurationBuilder{
30 | | let base_config: Value = from_str("{}").unwrap();
... |
89 | | }
90 | | }
| |_^
note: ...but the borrowed content is only valid for the anonymous lifetime #3 defined on the method
body at 66:5
--> src\lib.rs:66:5
|
66 | / pub fn define_bundle(&mut self, bundle_key: &str, sources: &Vec<ConfigurationSource>){
67 | | self.bundles.insert(bundle_key, sources);
68 | | }
| |_____^
error[E0312]: lifetime of reference outlives lifetime of borrowed content...
--> src\lib.rs:67:29
|
67 | self.bundles.insert(bundle_key, sources);
| ^^^^^^^^^^
|
note: ...the reference is valid for the lifetime 'a as defined on the impl at 27:1...
--> src\lib.rs:27:1
|
27 | / impl<'a> ConfigurationBuilder<'a>{
28 | |
29 | | pub fn new(base_source: &ConfigurationSource) -> ConfigurationBuilder{
30 | | let base_config: Value = from_str("{}").unwrap();
... |
89 | | }
90 | | }
| |_^
note: ...but the borrowed content is only valid for the anonymous lifetime #2 defined on the method
body at 66:5
--> src\lib.rs:66:5
|
66 | / pub fn define_bundle(&mut self, bundle_key: &str, sources: &Vec<ConfigurationSource>){
67 | | self.bundles.insert(bundle_key, sources);
68 | | }
| |_____^
我做错了什么?
答案 0 :(得分:2)
if
的输入参数具有编译器不知道的生命周期,或者比为结构定义的生命周期更长。
告诉编译器他们期望相同的生命周期可以解决问题:
define_bundle