类型别名上缺少生命周期说明符 [E0106]
missing lifetime specifier [E0106] on 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];
产生此错误:
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
,因此我们需要定义一个新的通用生命周期。
此代码:
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
,因此我们需要定义一个新的通用生命周期。