【发布时间】:2016-06-23 13:26:12
【问题描述】:
我正在尝试编写一个 Rust 函数,它接受一个正则表达式和一个字符串/字符串,并返回该正则表达式中所有命名捕获的 HashMap。代码如下:
use std::collections::HashMap;
use regex::Regex;
fn get_matches<'a>(line: &'a str, re: &Regex) -> HashMap<&'a str, &'a str> {
let mut results = HashMap::new();
match re.captures(line) {
None => { return results; },
Some(caps) => {
for (name, value) in caps.iter_named() {
if let Some(value) = value {
results.insert(name, value);
}
}
}
}
results
}
我得到这个编译器错误(Rust 1.9.0):
error: `caps` does not live long enough
for (name, value) in caps.iter_named() {
^~~~
note: reference must be valid for the lifetime 'a as defined on the block at 6:79...
fn get_matches<'a>(line: &'a str, re: &Regex) -> HashMap<&'a str, &'a str> {
let mut results = HashMap::new();
match re.captures(line) {
None => { return results; },
Some(caps) => {
...
note: ...but borrowed value is only valid for the match at 9:8
match re.captures(line) {
None => { return results; },
Some(caps) => {
for (name, value) in caps.iter_named() {
if let Some(value) = value {
results.insert(name, value);
...
但是,我不明白。 regex::Regex::captures return value has a lifetime of 't, which is the same lifetime as the string,在这种情况下,这意味着'a',regex::Captures::iter_named returned value also has the same lifetime of 't,在这种情况下是'a,这意味着(name, value) for that thing也应该是't,在这种情况下是'a .
我的函数定义有一个HashMap,它使用'a 的生命周期,所以不应该是Just Work(tm) 吗?我想我理解为什么你不能使用局部变量,除非你返回它,但在这种情况下,我使用的引用应该足够长,对吧?
我想我可以将.clone() 的所有内容都发送到String,但我很好奇我是否可以仅使用参考来编写此内容。那不是应该更有效率吗?我对 Rust 有点陌生,所以我正在尝试以一种正确、先进的方式去探索和做事。
【问题讨论】:
标签: string reference rust lifetime