rust - 迭代 Rust 中的命名正则表达式组

标签 rust

我希望将匹配项中的所有命名组提取到 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> 一生在哪里'rroute.regex的那个和一生'tpath的那个
  • 这个迭代器产生一个 Captures<'t> , 仅链接到 path 的生命周期
  • 谁的方法 iter_named(&'t self) 产生 SubCapture<'t> 本身链接到 path 的生命周期 cap 的生命周期
  • 这个迭代器产生一个 (&'t str, Option<&'t str>)这样 HashMap 的键和值链接到 path 的生命周期 cap 的生命周期

因此,不幸的是不可能有 HashMapcap 长寿变量,因为此变量被代码用作“标记”以保持包含组的缓冲区处于事件状态。

恐怕没有重大重组的唯一解决方案是返回 HashMap<String, String> ,尽管如此令人不满意。我还想到,单个捕获组可能会匹配 多次 次,不确定您是否愿意为此烦恼。

关于rust - 迭代 Rust 中的命名正则表达式组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39184481/

相关文章:

parsing - 为具有递归结构(如嵌套列表)的上下文敏感标记语言编写词法分析器

Rust 不能返回引用局部变量的值

import - Rust:根目录中没有 `module`

rust - Rust 为什么很难找到传递依赖?

rust - 如何表示共享可变状态?

rust - 标准是否定义了 Result<T, dyn std::error::Error> 的别名?

rust - 如何包含来自同一项目的另一个文件的模块?

rust - 如何用未装箱的闭包替换 proc?

rust - 轻松将第三方错误转换为字符串

lambda - 为什么这个闭包需要内联或 `dyn` ? `dyn` 在这里做什么?