Rust类型别名导致生命周期问题

时间:2020-09-25 11:57:04

标签: rust lifetime

我试图通过引入类型别名来缩短函数签名。 参数的类型说明如下:

writer: Arc<Mutex<&mut (dyn AsyncWrite + Unpin + Send + Sync)>>  // working

我认为可以通过引入这种类型的别名来缩短

pub type RefAsyncWriter<'a> = &'a mut (dyn AsyncWrite + Unpin + Send + Sync);

所以type参数变为

writer: Arc<Mutex<RefAsyncWriter>>  // error[E0726]: implicit elided lifetime not allowed here

不幸的是,这种变化使我终身难堪。

在这里我做了一个简短的例子

use tokio::io::AsyncWrite;
use tokio::fs::File;
use std::sync::{Arc,Mutex};
use std::path::PathBuf;
pub type RefAsyncWriter<'a> = &'a mut (dyn AsyncWrite + Unpin + Send + Sync);

#[tokio::main]
async fn main() {
    let f = File::create(PathBuf::from("/tmp/test.txt")).await.unwrap();
    w(Arc::new(Mutex::new(&mut f)));
}

async fn w(writer: Arc<Mutex<RefAsyncWriter>>) {
  // TODO
}

结果如下

Compiling playground v0.0.1 (/playground)
error[E0726]: implicit elided lifetime not allowed here
  --> src/main.rs:13:31
   |
13 | async fn w (writer: Arc<Mutex<RefAsyncWriter>>) {}
   |                               ^^^^^^^^^^^^^^- help: indicate the anonymous lifetime: `<'_>`

error: aborting due to previous error

(请参阅:https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=eb46708a9df66efa0de419a8d98490cf

如果有人可以向我解释(1)是否有办法使它起作用,也许(2)为什么类型别名实际上会对编译器产生如此大的影响,所以会很有帮助。

非常感谢。

1 个答案:

答案 0 :(得分:3)

由于在类型别名中引入了显式生存期'a,因此在使用此类型时需要指定它。

async fn w<'a>(writer: Arc<Mutex<RefAsyncWriter<'a>>>) {}

它似乎在您提供的操场上工作。

正如编译器建议的那样,匿名litetime是等效的。

async fn w(writer: Arc<Mutex<RefAsyncWriter<'_>>>) {}

函数的原始版本(在writer:之后记下的很长的类型在某种程度上等效于this documentation中的print1()print2()print3() 。 如果引入引用作为参数,则此函数必定存在生命周期参数;当这辈子都不可能混淆时,省略就带来了一些舒适,可以节省一些击键。

在定义一个包含引用的类型别名时,编译器希望我们使生存期明确,这可能是为了防止使用此类型别名的人忘记内部有一个引用 hidden 。 然后,使用此类型别名需要使用<'...>表示法。 但是同样,当使用时不会造成混淆时,匿名生存期<'_>可以节省一些击键,避免两次(在函数名之后和在参数中)两次写入<'a>

相关问题