这段代码:
use std::fmt;
use std::result::Result::{self, Ok, Err};
#[derive(Clone)]
#[derive(Copy)]
enum Tile {
White,
Black,
Empty
}
type Board = &[[Tile; 19]; 19];
产生这个错误:
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.
我很难找到任何解释什么是生命周期说明符以及为什么我需要在类型别名声明中使用它的内容。
最佳答案
简短的回答是
type Board<'a> = &'a [[Tile; 19]; 19];
Rust 对于泛型参数总是明确的。生命周期也是通用参数。想象一下,您将对 Tile
类型进行通用化。
type Board = &[[T; 19]; 19];
这会导致有关 T
不存在的错误(除非您定义了一个名为 T
的实际类型)。但是您希望能够将 Board
用于任何内部类型。所以你需要做的是在定义中添加一个通用参数:
type Board<T> = &[[T; 19]; 19];
因此,无论何时使用Board
类型别名,您还需要传递T
类型。
回到我们的生命期问题。我们的类型别名有一个引用。我们不知道这个引用的生命周期是多少。很少需要指定生命周期的原因是 lifetime-elision .这是您需要指定生命周期的情况之一,因为您希望在使用 Board
的所有位置确定生命周期,就像您使用 &[[Tile; 一样。 19]; 19]
直接无处不在。在类型别名定义中,唯一可用的生命周期是 'static
,因此我们需要定义一个新的通用生命周期。
关于rust - 类型别名上缺少生命周期说明符 [E0106],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30610493/