我希望将匹配项中的所有命名组提取到 HashMap 中,但在尝试编译此代码时遇到了“生命周期不够长”的错误:
extern crate regex;
use std::collections::HashMap;
use regex::Regex;
pub struct Route {
regex: Regex,
}
pub struct Router<'a> {
pub namespace_seperator: &'a str,
routes: Vec<Route>,
}
impl<'a> Router<'a> {
// ...
pub fn path_to_params(&self, path: &'a str) -> Option<HashMap<&str, &str>> {
for route in &self.routes {
if route.regex.is_match(path) {
let mut hash = HashMap::new();
for cap in route.regex.captures_iter(path) {
for (name, value) in cap.iter_named() {
hash.insert(name, value.unwrap());
}
}
return Some(hash);
}
}
None
}
}
fn main() {}
这是错误输出:
error: `cap` does not live long enough
--> src/main.rs:23:42
|>
23 |> for (name, value) in cap.iter_named() {
|> ^^^
note: reference must be valid for the anonymous lifetime #1 defined on the block at 18:79...
--> src/main.rs:18:80
|>
18 |> pub fn path_to_params(&self, path: &'a str) -> Option<HashMap<&str, &str>> {
|> ^
note: ...but borrowed value is only valid for the for at 22:16
--> src/main.rs:22:17
|>
22 |> for cap in route.regex.captures_iter(path) {
|> ^
显然,关于 Rust 生命周期,我还有一两件事需要学习。
最佳答案
让我们跟随生命线:
-
route.regex.captures_iter(path)
创建一个FindCapture<'r, 't>
一生在哪里'r
是route.regex
的那个和一生't
是path
的那个 - 这个迭代器产生一个
Captures<'t>
, 仅链接到path
的生命周期 - 谁的方法
iter_named(&'t self)
产生SubCapture<'t>
本身链接到path
的生命周期和cap
的生命周期 - 这个迭代器产生一个
(&'t str, Option<&'t str>)
这样HashMap
的键和值链接到path
的生命周期和cap
的生命周期
因此,不幸的是不可能有 HashMap
比 cap
长寿变量,因为此变量被代码用作“标记”以保持包含组的缓冲区处于事件状态。
恐怕没有重大重组的唯一解决方案是返回 HashMap<String, String>
,尽管如此令人不满意。我还想到,单个捕获组可能会匹配 多次 次,不确定您是否愿意为此烦恼。
关于rust - 迭代 Rust 中的命名正则表达式组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39184481/