【发布时间】:2018-12-01 23:40:47
【问题描述】:
我正在尝试创建一个带有字段的结构,该字段在 F 上是通用的,其中 F 实现类似:Fn(&mut Compiler, &[Token]) -> &Token。唯一的问题是,我不确定如何在 Fn 特征上定义生命周期,它满足返回的 &Token 引用 &[Token] 切片中作为参数提供的数据的约束。到目前为止,我尝试过的一切都引发了神秘的错误。
这是一个演示代码的 MVCE(没有任何生命周期):
struct Compiler;
#[derive(Debug)]
struct Token(usize);
impl Compiler {
// missing lifetime paramters here
fn meth(&mut self, tokens: &[Token]) -> &Token {
tokens.get(0).unwrap()
}
}
// missing lifetime paramters here
struct Rule<F> where F: Fn(&mut Compiler, &[Token]) -> &Token {
func: F
}
fn main() {
let mut c = Compiler;
let tokens = vec![Token(0), Token(1), Token(2)];
let r = Rule { func: Compiler::meth };
(r.func)(&mut c, &tokens);
}
自然编译失败,报错:
Compiling playground v0.0.1 (/playground)
error[E0106]: missing lifetime specifier
--> src/main.rs:11:56
|
11 | struct Rule<F> where F: Fn(&mut Compiler, &[Token]) -> &Token {
| ^ expected lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from argument 1 or argument 2
我尝试在这里和那里添加生命周期说明符,四处移动,但似乎没有任何效果。我真的很感激对这个问题的任何见解。谢谢!
【问题讨论】:
-
play.rust-lang.org/…,但不清楚你想做什么。
-
@Stargateur 我以前从未见过
where for语法,它记录在哪里? -
@jonny 这是一个更高等级的特征界限。见doc.rust-lang.org/nomicon/hrtb.html
-
@jonny 或 doc.rust-lang.org/reference/…,不幸的是,这没有很好的记录。这种功能非常先进,Rust 尝试使用 GAT 对其进行改进。这是一个广泛的话题。