Har*_*aka 5 struct compiler-errors hashmap rust borrow-checker
我的 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我不希望 ConfigurationBuilder 实例中的包 Hashmap 拥有传递给方法的bundle_keys 或sources 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 | | }
| |_____^
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
您的输入参数define_bundle具有编译器不知道满足或超过为结构定义的生命周期的生命周期。
告诉编译器他们期望相同的生命周期可以解决问题:
pub fn define_bundle(&mut self, bundle_key: &'a str, sources: &'a Vec<ConfigurationSource>) {
// ^^----------------^^ same lifetimes as the struct fields expect
self.bundles.insert(bundle_key, sources);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1562 次 |
| 最近记录: |