我已经阅读了Rust Book和一些其他关于生命周期的教程。我之前认为生命周期就像是一个函数接受的泛型参数,你将其分配到输入和输出参数后就会限制这些参数的生命周期。例如fn find<'a, 'b>(pattern: &'a str, text: &'b str) -> &'b str
表示任何传递给text的参数需要具有至少与返回值一样长的生命周期。但是,在我写的一个程序中,我遇到了一个错误,这使我认为我对生命周期的理解存在某些根本性的误解。
下面是该函数的签名:
async fn check_git(requester: &mut Requester) -> Result<()>
Result
是 anyhow::Result
,如果需要的话。
当我编译时,出现错误:
error[E0726]: implicit elided lifetime not allowed here
--> src/scanner/git.rs:5:40
|
5 | pub async fn check_git(requester: &mut Requester) -> Result<()> {
| ^^^^^^^^^- help: indicate the anonymous lifetime: `<'_>`
|
= note: assuming a `'static` lifetime...
我通过添加生命周期参数来解决编译错误:
async fn check_git<'a>(requester: &mut Requester<'a>) -> Result<()>
。
我理解requester
不能有静态生命周期,因为我调用check_git
的方式,传入的requester
生命周期是调用check_git
的函数的作用域。但我不明白我加入的生命周期注释确切的含义。我初学者的理解是,
fn check_git<'a>
只是指定'a
是一个通用参数,然后当您将'a
应用到多个参数时,它会限制这些参数的生命周期关系。但是当我只将'a
应用于一个参数时,生命周期注释没有增加任何约束或含义吗?我要添加生命周期参数的
Requester
结构体定义为:struct Requester<'a> {
client: SendRequest<Body>,
resp: Option<Response<Body>>,
host: &'a str,
port: u16,
ctx: &'a SslContextRef,
}