类型别名上缺少生存期说明符

类型别名上缺少生存期说明符

本文介绍了类型别名上缺少生存期说明符[E0106]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

此代码:

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.

我很难找到可以解释生命周期说明符的原因,以及为什么在类型别名声明中需要它的原因.

I'm having a hard time finding anything that explains what a lifetime specifier is and why I would need that on a type alias declaration.

推荐答案

简短的答案是

type Board<'a> = &'a [[Tile; 19]; 19];


关于泛型参数,Rust始终是明确的.生命周期也是通用参数.假设您对Tile类型是通用的.


Rust is always explicit about generic arguments. Lifetimes also are generic arguments. Imagine you'd be generic over the Tile type.

type Board = &[[T; 19]; 19];

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

This would cause an error about T not existing (except if you defined an actual type named T). But you'd like to be able to use Board for any inner type. So what you'd need to do is to add a generic argument to the definition:

type Board<T> = &[[T; 19]; 19];

因此,每当使用Board类型别名时,还需要传递T类型.

So whenever you use the Board type alias, you also need to pass the T type.

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

Back to our lifetime issue. Our type alias has a reference. We don't know what the lifetime of this reference is. The reason why you rarely need to specify a lifetime is lifetime-elision. This is one of the cases where you need to specify the lifetime, since you want the lifetime to be determined at all locations where you use Board, like as if you used &[[Tile; 19]; 19] everywhere directly. At the type alias definition the only available lifetime is 'static, so we need to define a new generic one.

这篇关于类型别名上缺少生存期说明符[E0106]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:38