I have a fairly simple bit of code. I have a feeling I need to use a lifetime to accomplish this but I'm stumped right now.
parse_string
is a function that accepts a reference to a string, and returns a closure to be used later, here's the code:
fn main() {
let parse_this = parse_string(&String::from("Hello!"));
println!("{}", parse_this("goodbye!"));
}
fn parse_string(string: &String) -> impl Fn(&str) -> &String {
return |targetString| {
// pretend there is parsing logic
println!("{}", targetString);
return string;
};
}
Compiler error:
error: cannot infer an appropriate lifetime
--> src/main.rs:7:12
|
6 | fn parse_string(string: &String) -> impl Fn(&str) -> &String {
| ------------------------ this return type evaluates to the `'static` lifetime...
7 | return |targetString| {
| ____________^
8 | | // pretend there is parsing logic
9 | | println!("{}", targetString);
10 | | return string;
11 | | };
| |_____^ ...but this borrow...
|
note: ...can't outlive the anonymous lifetime #1 defined on the function body at 6:1
--> src/main.rs:6:1
|
6 | / fn parse_string(string: &String) -> impl Fn(&str) -> &String {
7 | | return |targetString| {
8 | | // pretend there is parsing logic
9 | | println!("{}", targetString);
10 | | return string;
11 | | };
12 | | }
| |_^
help: you can add a constraint to the return type to make it last less than `'static` and match the anonymous lifetime #1 defined on the function body at 6:1
|
6 | fn parse_string(string: &String) -> impl Fn(&str) -> &String + '_ {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0312]: lifetime of reference outlives lifetime of borrowed content...
--> src/main.rs:10:16
|
10 | return string;
| ^^^^^^
|
note: ...the reference is valid for the anonymous lifetime #2 defined on the body at 7:12...
--> src/main.rs:7:12
|
7 | return |targetString| {
| ____________^
8 | | // pretend there is parsing logic
9 | | println!("{}", targetString);
10 | | return string;
11 | | };
| |_____^
note: ...but the borrowed content is only valid for the anonymous lifetime #1 defined on the function body at 6:1
--> src/main.rs:6:1
|
6 | / fn parse_string(string: &String) -> impl Fn(&str) -> &String {
7 | | return |targetString| {
8 | | // pretend there is parsing logic
9 | | println!("{}", targetString);
10 | | return string;
11 | | };
12 | | }
| |_^