Hello friends, I hope you're doing well. I'm sharing the steps I tried, along with the errors I encountered, and the code snippets below. I would really appreciate it if you could help me understand this simple code.
In my function, I receive a list of strings as input from the user (like vec!["OXCTestHook"];
). For example, since I don't know exactly how many entries there will be, I use the following parameter type:
names: impl IntoIterator<Item = impl AsRef<str>>,
In one part of the function, I need to loop through this list and apply an operation on each item one by one:
for name in names {
let new_property = create_and_import_object_into_hook(name, allocator);
obj_expr.properties.push(new_property);
}
The error I get at this part is:
rust-analyzer: expected &str, found String
So, I tried converting the names into Vec<String>
before the loop to make sure I could pass &str
to my function:
let names: Vec<String> = names.into_iter().map(|n| n.as_ref().to_string()).collect();
for name in names {
let new_property = create_and_import_object_into_hook(&name, allocator);
obj_expr.properties.push(new_property);
}
However, the error I got was:
rustc: `name` does not live long enough
borrowed value does not live long enough
Full error:
error[E0597]: `name` does not live long enough
--> src/parser/ast.rs:188:71
|
187 | for name in names {
| ---- binding `name` declared here
188 | let new_property = create_and_import_object_into_hook(&name, allocator);
| ^^^^^ borrowed value does not live long enough
189 | obj_expr.properties.push(new_property);
| -------- borrow later used here
190 | }
| - `name` dropped here while still borrowed
For more information about this error, try `rustc --explain E0597`
After that, I attempted converting each string to a reference. I don't know why ( ), but I thought maybe this would solve the problem:
name.as_ref()
&name.as_ref()
Unfortunately, I kept getting the same repeated error:
rustc: `name` does not live long enough
borrowed value does not live long enough
I also tried random meaningless things like taking a reference and dereferencing it again (&*
), hoping it might work.
Previously, with help from the community, I added this function to my project:
fn create_and_import_object_into_hook<'a>(
name: &'a str,
allocator: &Allocator,
) -> ObjectPropertyKind<'a> {
In that function, I stated that each name
has a lifetime extending to the final output. However, I'm still getting the same errors.
These are all the steps I've tried and the errors I encountered. Sorry for the long post. I just wanted to see with your help what the problem might be that I can't execute such a simple loop here.
Thank you in advance.
The code is available at the following link:
Thank you in advance