我不完全了解lifetime,但我认为b
的lifetime将会在self
之前结束。
那么,如何编辑这段代码?我需要复制内存中的某些内容吗?如果我创建一个新的实例,它的lifetime必须符合这种情况。
pub struct Formater {
layout: &'static str,
}
impl Formater {
pub fn new(layout: &'static str) -> Formater {
let regex = Regex::new(r"%\{([a-z]+)(?::(.*?[^\\]))?\}").unwrap();
let b = regex.replace_all(layout, "{}");
return Formater {
layout: &b,
};
}
}
错误:
error: `b` does not live long enough
--> src/format.rs:16:22
|
16 | layout: &b,
| ^ does not live long enough
17 | };
18 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
layout
声明为String
而不是&'static str
。https://dev59.com/OWAf5IYBdhLWcg3w52I_ - kennytm&str
? - wimhFormater
中的&'
部分不太明白,因为b
并不是一个静态字符串,你不能给它一个静态引用,对吗? - Netwave