【发布时间】:2019-10-02 19:03:48
【问题描述】:
我有一段相当简单的代码。我有一种感觉,我需要用一生来完成这件事,但我现在很难过。
parse_string 是一个函数,它接受对字符串的引用,并返回一个闭包供以后使用,代码如下:
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;
};
}
编译器错误:
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 | | }
| |_^
【问题讨论】: