gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:36:15 24 4
gpt4 key购买 nike

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

我有一个名为 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 个十六进制字符映射到 Branch,例如3d2.

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

所以,我试图通过将 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 } )
}

将 move 放在第二个 .map 上有效。

关于使用 Combine 的 Rust 所有权和生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48707861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com