这取决于您如何创建对象.对于您的情况,您使用matches函数来创建Matches
.
让我们来判断一下matches
的定义:
pub fn matches<'a, P>(&'a self, pat: P) -> Matches<'a, P>
where
P: Pattern<'a>,
当你呼叫my_string.matches(pat);
的时候,'a
就变成了my_string
的生命周期.(my_string
等于&'static str
,'a
等于'static
)
当my_string
输入为String
时,它将是arbitrary lifetime.
在本例中,您不能显式声明生存期,它将从my_string中获取,
但请考虑这样一个函数:
use std::str::Matches;
fn count_ings<'a>(source: &'a str) -> usize {
let matches: Matches<&'a str> = source.matches("ing"); //explicitly declared
matches.count()
}
fn main() {
let my_string = "Hello. I have a string and a substring.".to_string();
println!("'ing' count: {}", count_ings(&my_string));
}
我认为这为matches
var带来了轻微的保护,但如果你想使用它,那就使用它吧.此外,您甚至可以 Select 退出终身声明,由于终身省略,不需要添加通配符.
let matches: Matches<_> = source.matches("ing"); //replace with the line above.