Skip to content

Commit b4556a1

Browse files
jldBurntSushi
authored andcommitted
Loosen lifetime bounds on accessing named captures via Index.
The current definition equates the lifetime of the strings being matched/captured and the string used as the capture name. The latter is usually `'static` (string literals), which leads to confusing [borrow-check errors][err] on reasonable-looking code. This change declares the two lifetimes as separate; this should be a strict increase in the set of `impl` instances, so it's a minor version bump. [err][]: https://gist.github.com/jld/476a13a00ad05bd99a63
1 parent 899f755 commit b4556a1

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/re.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -992,11 +992,11 @@ impl<'t> Index<usize> for Captures<'t> {
992992
///
993993
/// # Panics
994994
/// If there is no group named by the given value.
995-
impl<'t> Index<&'t str> for Captures<'t> {
995+
impl<'t, 'i> Index<&'i str> for Captures<'t> {
996996

997997
type Output = str;
998998

999-
fn index<'a>(&'a self, name: &str) -> &'a str {
999+
fn index<'a>(&'a self, name: &'i str) -> &'a str {
10001000
match self.name(name) {
10011001
None => panic!("no group named '{}'", name),
10021002
Some(ref s) => s,
@@ -1295,4 +1295,16 @@ mod test {
12951295
let cap = re.captures("abc").unwrap();
12961296
let _ = cap["bad name"];
12971297
}
1298+
1299+
#[test]
1300+
fn test_cap_index_lifetime() {
1301+
// This is a test of whether the types on `caps["..."]` are general
1302+
// enough. If not, this will fail to typecheck.
1303+
fn inner(s: &str) -> usize {
1304+
let re = Regex::new(r"(?P<number>\d+)").unwrap();
1305+
let caps = re.captures(s).unwrap();
1306+
caps["number"].len()
1307+
}
1308+
assert_eq!(inner("123"), 3);
1309+
}
12981310
}

0 commit comments

Comments
 (0)