类型别名上缺少生命周期说明符[E0106]

mav*_*vix 5 lifetime rust type-alias

这段代码:

use std::fmt;
use std::result::Result::{self, Ok, Err};

#[derive(Clone)]
#[derive(Copy)]
enum Tile {
    White,
    Black,
    Empty
}
type Board = &[[Tile; 19]; 19];
Run Code Online (Sandbox Code Playgroud)

产生此错误:

Compiling go v0.1.0 (file:///home/max/gits/go_rusty)
src/main.rs:12:14: 12:31 error: missing lifetime specifier [E0106]
src/main.rs:12 type Board = &[[Tile; 19]; 19];
                            ^~~~~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `go`.

To learn more, run the command again with --verbose.
Run Code Online (Sandbox Code Playgroud)

我很难找到任何解释生命周期说明符是什么以及为什么我需要在类型别名声明上.

oli*_*obk 9

简短的回答是

type Board<'a> = &'a [[Tile; 19]; 19];
Run Code Online (Sandbox Code Playgroud)

Rust总是明确关于泛型参数.生命周期也是一般参数.想象一下,你在这种Tile类型上是通用的.

type Board = &[[T; 19]; 19];
Run Code Online (Sandbox Code Playgroud)

这将导致T不存在的错误(除非您定义了名为的实际类型T).但是你希望能够Board用于任何内部类型.所以你需要做的是在定义中添加一个泛型参数:

type Board<T> = &[[T; 19]; 19];
Run Code Online (Sandbox Code Playgroud)

因此,无论何时使用Board类型别名,您还需要传递T类型.

回到我们的终身问题.我们的类型别名有一个参考.我们不知道这个引用的生命周期是什么.您很少需要指定生命周期的原因是life-elision.这是您需要指定生命周期的情况之一,因为您希望在您使用的所有位置确定生命周期Board,就像您&[[Tile; 19]; 19]直接在任何地方使用一样.在类型别名定义中,唯一可用的生命周期是'static,因此我们需要定义一个新的通用生命周期.