@@ -976,6 +976,12 @@ impl<'t> Captures<'t> {
976
976
977
977
/// Get a group by index.
978
978
///
979
+ /// `'t` is the lifetime of the matched text.
980
+ ///
981
+ /// The text can't outlive the `Captures` object if this method is
982
+ /// used, because of how `Index` is defined (normally `a[i]` is part
983
+ /// of `a` and can't outlive it); to do that, use `at()` instead.
984
+ ///
979
985
/// # Panics
980
986
/// If there is no group at the given index.
981
987
impl < ' t > Index < usize > for Captures < ' t > {
@@ -990,13 +996,20 @@ impl<'t> Index<usize> for Captures<'t> {
990
996
991
997
/// Get a group by name.
992
998
///
999
+ /// `'t` is the lifetime of the matched text and `'i` is the lifetime
1000
+ /// of the group name (the index).
1001
+ ///
1002
+ /// The text can't outlive the `Captures` object if this method is
1003
+ /// used, because of how `Index` is defined (normally `a[i]` is part
1004
+ /// of `a` and can't outlive it); to do that, use `name` instead.
1005
+ ///
993
1006
/// # Panics
994
1007
/// If there is no group named by the given value.
995
- impl < ' t > Index < & ' t str > for Captures < ' t > {
1008
+ impl < ' t , ' i > Index < & ' i str > for Captures < ' t > {
996
1009
997
1010
type Output = str ;
998
1011
999
- fn index < ' a > ( & ' a self , name : & str ) -> & ' a str {
1012
+ fn index < ' a > ( & ' a self , name : & ' i str ) -> & ' a str {
1000
1013
match self . name ( name) {
1001
1014
None => panic ! ( "no group named '{}'" , name) ,
1002
1015
Some ( ref s) => s,
@@ -1295,4 +1308,16 @@ mod test {
1295
1308
let cap = re. captures ( "abc" ) . unwrap ( ) ;
1296
1309
let _ = cap[ "bad name" ] ;
1297
1310
}
1311
+
1312
+ #[ test]
1313
+ fn test_cap_index_lifetime ( ) {
1314
+ // This is a test of whether the types on `caps["..."]` are general
1315
+ // enough. If not, this will fail to typecheck.
1316
+ fn inner ( s : & str ) -> usize {
1317
+ let re = Regex :: new ( r"(?P<number>\d+)" ) . unwrap ( ) ;
1318
+ let caps = re. captures ( s) . unwrap ( ) ;
1319
+ caps[ "number" ] . len ( )
1320
+ }
1321
+ assert_eq ! ( inner( "123" ) , 3 ) ;
1322
+ }
1298
1323
}
0 commit comments