简体   繁体   English

延长生锈的借用寿命

[英]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.

相关问题 借用vs变异借用生命中的奇怪失败 - Borrow vs mutable borrow strange failure in lifetimes 为什么 Rust 需要明确的生命周期? - Why are explicit lifetimes needed in Rust? 在 Rust 中为静态生命周期的悬空引用和建议而苦苦挣扎 - Struggling with dangling references and suggestions for static lifetimes in Rust Rust - 为借用特征指定生命周期参数 - Rust - Specifying a Lifetime Parameter for the Borrow Trait Rust 借用检查器在 if 语句中抛出错误 - Rust borrow checker throwing error in if statement Rust 是否会缩短生命周期以满足对其定义的约束? - Does Rust narrow lifetimes to satisfy constraints defined on them? 在Rust中,如何将两个对象的生命周期明确地绑定在一起,而不是相互引用? - In Rust, how do you explicitly tie the lifetimes of two objects together, without referencing eachother? 我使用什么生命周期来创建循环引用彼此的 Rust 结构? - What lifetimes do I use to create Rust structs that reference each other cyclically? 为什么在将变量移动到 scope 后 Rust 编译器错误“不能作为不可变借用,因为它也作为可变借用”? - Why does the Rust compiler error with "cannot borrow as immutable because it is also borrowed as mutable" after moving the variable into a scope? 在Vec中混合引用的生存期 - Mix lifetimes of references in Vec
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM