[英]Extending borrow lifetimes in rust
我正在嘗試解析一系列tokentrees,但是當我嘗試實現我的解析特性時,我得到一個與參考生命周期相關的錯誤。 我認為創建一個盒裝版本會隨着引用計數或生命周期的任何問題而移動。 代碼如下。
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"),
}
}
}
我得到的錯誤使問題清楚,但我找不到任何有關解決這個問題的信息。
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
返回對象本身的引用,如:
fn parse(&self) -> &str
引用只能持續與對象一樣長,否則它將指向無效數據。
編輯:它怎么可能,可能工作
你要跟蹤你的令牌化字符串的壽命和你的一生令牌綁定到該輸入:
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.