[英]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<®ex::Regex, &str>, [closure@src\lsystem.rs:26:37: 26:70]>, combine::combinator::Map<combine::regex::Find<®ex::Regex, &str>, [closure@src\lsystem.rs:26:37: 26:70]>, combine::combinator::Map<combine::regex::Find<®ex::Regex, &str>, [closure@src\lsystem.rs:26:37: 26:70]>, combine::combinator::Map<combine::regex::Find<®ex::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.