[英]Extending borrow lifetimes in rust
I'm trying to parse a series to tokentrees, but when I try to implement my parsing trait I get an error related to reference lifetimes. 我正在尝试解析一系列tokentrees,但是当我尝试实现我的解析特性时,我得到一个与参考生命周期相关的错误。 I thought creating a boxed version would move around any issues with reference counts or lifetimes.
我认为创建一个盒装版本会随着引用计数或生命周期的任何问题而移动。 The code is as follows.
代码如下。
impl Parse for TokenTree {
fn parse(&mut self) -> Tree {
match self.clone() {
TtDelimited(_, y) => {
let mut y2 = box (*y).clone();
match y2.delim {
token::DelimToken::Paren => y2.parse(),
_ => panic!("not done yet"),
}
}
TtToken(_, t) => E(t),
_ => panic!("not done yet"),
}
}
}
the errors I get make the issue clear, but I can't find any information on solving this particular issue. 我得到的错误使问题清楚,但我找不到任何有关解决这个问题的信息。
35:51 error: `*y2` does not live long enough
token::DelimToken::Paren => y2.parse(),
^~
42:6 note: reference must be valid for the anonymous lifetime #1 defined on the block at 30:31...
fn parse(&mut self) -> Tree{
match self.clone(){
TtDelimited(_, y) => {
let mut y2 = box () (*y).clone();
match y2.delim{
token::DelimToken::Paren => y2.parse(),
...
38:14 note: ...but borrowed value is only valid for the block at 32:33
TtDelimited(_, y) => {
let mut y2 = box () (*y).clone();
match y2.delim{
token::DelimToken::Paren => y2.parse(),
_ => panic!("not done yet"),
}
In this code: 在这段代码中:
{
let mut y2 = box (*y).clone();
match y2.delim {
token::DelimToken::Paren => y2.parse(),
_ => panic!("not done yet"),
}
}
You create y2
, which will only live until the block exits. 您创建
y2
,它只会在块退出之前生效。 You didn't include your trait, but my guess is that parse
returns a reference to the object itself, something like: 你没有包含你的特性,但我的猜测是,
parse
返回对象本身的引用,如:
fn parse(&self) -> &str
The reference can only last as long as the object, otherwise it'd point to invalid data. 引用只能持续与对象一样长,否则它将指向无效数据。
Edit: How it could maybe, possibly work 编辑:它怎么可能,可能工作
You have to track the lifetime of the string you are tokenizing and tie your tokens lifetime to that input: 你要跟踪你的令牌化字符串的寿命和你的一生令牌绑定到该输入:
enum Token<'a> {
Identifier(&'a str),
Whitespace(&'a str),
}
trait Parser {
// Important! The lifetime of the output is tied to the parameter `input`,
// *not* to the structure that implements this!
fn parse<'a>(&self, input: &'a str) -> Token<'a>;
}
struct BasicParser;
impl Parser for BasicParser {
fn parse<'a>(&self, input: &'a str) -> Token<'a> {
Token::Identifier(input)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.