延长锈的借用寿命 [英] 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. 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"),
}
推荐答案
在此代码中:
{
let mut y2 = box (*y).clone();
match y2.delim {
token::DelimToken::Paren => y2.parse(),
_ => panic!("not done yet"),
}
}
您创建y2
,它将一直存在直到该块退出.您没有包括特征,但是我猜测parse
返回对对象本身的引用,例如:
You create y2
, which will only live until the block exits. You didn't include your trait, but my guess is that parse
returns a reference to the object itself, something like:
fn parse(&self) -> &str
引用只能与对象一样长,否则将指向无效数据.
The reference can only last as long as the object, otherwise it'd point to invalid data.
它可能如何运作
您必须跟踪要标记化的字符串的生存期,并且将标记的生存期与该输入相关联:
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)
}
}
这篇关于延长锈的借用寿命的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!