繁体   English   中英

使用 Combine 的 Rust 所有权和生命周期

[英]Rust Ownership and Lifetimes using Combine

我已经阅读了关于所有权和生命周期的文档,我想我理解它们,但我在处理特定代码时遇到了麻烦。

我有一个名为Branch的结构,如下所示:

struct Branch {
    slot: u8,
    yaw: u8,
    pitch: u8,
    length: u8
}

我正在使用combine库(它是一个解析器组合器)将一个字符串解析为一个分支。 解析器如下所示:

let hex_re = Regex:new(r"[0-9a-fA-F]").unwrap();
let hex = || find(&hex_re).map(|s| u8::from_str_radix(s, 16));
let branch = |length: u8| {
    (hex(), hex(), hex())
        .map( |t| (t.0.unwrap(), t.1.unwrap(), t.2.unwrap()) )
        .map( |(slot,yaw,pitch)| Branch { slot, yaw, pitch, length } )
}

解析器相当简单,第一个hex采用匹配单个十六进制字符的正则表达式并将其映射到 u8。 第二个branch将 3 个十六进制字符映射到一个分支,例如 3d2。

当我调用解析器branch(1).parse("3d2") ,问题出现了,编译器报告错误'length' does not live long enough 我想我理解这个错误,如果我没有弄错的话,那是因为当闭包完成时length超出了范围,因此即使新创建的分支仍在使用length变量,它也会被释放。

所以,我试图通过将length: u8转换为length: &u8来解决这个问题:

let branch = |len: &u8| {
    (hex(), hex(), hex())
        .map( |t| (t.0.unwrap(), t.1.unwrap(), t.2.unwrap()) )
        .map( |(slot,yaw,pitch)| Branch { slot, yaw, pitch, length: *len } )
};

// calling the parser
branch(&(1 as u8)).parse("3d2");

但这会导致此错误:

type of expression contains references that are not valid during the expression: `combine::combinator::Map<combine::combinator::Map<(combine::combinator::Map<combine::regex::Find<&regex::Regex, &str>, [closure@src\lsystem.rs:26:37: 26:70]>, combine::combinator::Map<combine::regex::Find<&regex::Regex, &str>, [closure@src\lsystem.rs:26:37: 26:70]>, combine::combinator::Map<combine::regex::Find<&regex::Regex, &str>, [closure@src\lsystem.rs:26:37: 26:70]>, combine::combinator::Map<combine::regex::Find<&regex::Regex, &str>, [closure@src\lsystem.rs:26:37: 26:70]>), [closure@src\lsystem.rs:30:19: 30:65]>, [closure@src\lsystem.rs:31:19: 31:80 length:&&u8]>`

我不知道这个错误是关于什么的。 任何帮助将非常感激。

这解决了它:

let hex_re = Regex:new(r"[0-9a-fA-F]").unwrap();
let hex = || find(&hex_re).map(|s| u8::from_str_radix(s, 16));
let branch = |length: u8| {
    (hex(), hex(), hex())
        .map( |t| (t.0.unwrap(), t.1.unwrap(), t.2.unwrap()) )
        .map( move |(slot,yaw,pitch)| Branch { slot, yaw, pitch, length } )
}

将移动放在第二个 .map 作品上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM