沿多个结构共享 &str 与生命周期冲突
我有以下代码:
pub trait Regex: RegexClone {
fn check(&self) -> Result<u32,(/* errors should detail where it fails*/)>;
fn next(&self) -> Option<Box<dyn Regex>>;
}
pub trait RegexClone {
fn regex_clone(&self) -> Box<dyn Regex>;
}
pub struct PatternAnyCharacter<'a>{
string: &'a str
}
impl RegexClone for PatternAnyCharacter<'_> {
fn regex_clone(&self) -> Box<dyn Regex> {
return Box::new(PatternAnyCharacter {string: self.string})
}
}
impl Regex for PatternAnyCharacter<'_> {
fn check(&self) -> Result<u32, ()> {
if self.string.len() > 0 {
return Ok(1);
}
Err(())
}
fn next(&self) -> Option<Box<dyn Regex>> {
None
}
}
这个想法是,当我调用 regex_clone 时,我会得到一个新的 Box
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
--> src/lib.rs:63:25
|
63 | return Box::new(PatternAnyCharacter {string: self.string})
| ^^^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'_` as defined here...
--> src/lib.rs:61:41
|
61 | impl RegexClone for PatternAnyCharacter<'_> {
| ^^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:63:54
|
63 | return Box::new(PatternAnyCharacter {string: self.string})
| ^^^^^^^^^^^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the types are compatible
--> src/lib.rs:63:16
|
63 | return Box::new(PatternAnyCharacter {string: self.string})
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
= note: expected `Box<(dyn Regex + 'static)>`
found `Box<dyn Regex>`
我该如何解决这个问题,以便我可以与多个结构共享相同的字符串切片? 我考虑过将字符串切片完全作为成员并将其作为参数传递以进行检查,但希望我可以避免它。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想允许它借用
&self 的部分内容,您需要定义返回的
.:(dyn Regex
不能比&self
更长久的特征您也可以使用匿名生命周期(
Box
),但这更容易理解。)旁注:我不认为“克隆” “是这样一个正确的名字 功能。
You need to define at the trait that the returned
dyn Regex
can't outlive&self
if you want to allow it to borrow from parts of&self
.:(You can also use an anonymous lifetime (
Box<dyn Regex + '_>
), but this is easier to understand.)Side note: I don't think "clone" is the right name for such a function.