【发布时间】:2021-01-28 19:20:24
【问题描述】:
假设我有这个结构和这个特征:
#[derive(Debug)]
pub struct New<T>(T);
pub trait AsRefNew<'a> {
fn as_ref(&self) -> New<&'a str>;
}
也就是说,AsRefNew 特征允许返回具有给定生命周期的引用 'a 包装在 New 新类型中。此生命周期 'a 可能与 &self 参数的生命周期不同(并且将会不同)。
现在我可以为New(&str) 实现此特征,并使其输出的生命周期是包装的&str 的生命周期:
impl<'a> AsRefNew<'a> for New<&'a str> {
fn as_ref(&self) -> New<&'a str>{
New(self.0)
}
}
我的问题是我想为New(String) 实现特征,而这一次,我希望'a 实际匹配self 的生命周期。我的理解是这样的事情应该有效:
impl<'a> AsRefNew<'a> for New<String> where Self: 'a{
fn as_ref(&self) -> New<&'a str> {
New(self.0.as_str())
}
}
除非它没有:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src/main.rs:16:20
|
16 | New(self.0.as_str())
| ^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 15:5...
--> src/main.rs:15:5
|
15 | fn as_ref(&self) -> New<&'a str> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:16:13
|
16 | New(self.0.as_str())
| ^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 14:6...
--> src/main.rs:14:6
|
14 | impl<'a> AsRefNew<'a> for New<String> where Self: 'a{
| ^^
note: ...so that the expression is assignable
--> src/main.rs:16:9
|
16 | New(self.0.as_str())
| ^^^^^^^^^^^^^^^^^^^^
= note: expected `New<&'a str>`
found `New<&str>`
我尝试了生命周期和泛型的不同变体,但我找不到更好的方式来表达我在这种情况下希望'a 匹配'_。
目标是让这个 sn-p 工作:
fn main() {
// This works:
let a = String::from("Hey");
let b;
{
let c = New(a.as_str());
b = c.as_ref().0;
}
println!("{:?}", b);
// I would like that to work as well:
let a = String::from("Ho");
let b;
let c = New(a);
{
b = c.as_ref().0;
}
println!("{:?}", b);
}
有什么想法吗?
【问题讨论】:
-
我不确定这个问题是否可以回答,直到您详细说明“此生命周期
'a可能与&self参数的生命周期不同(并且将会)”并提供一些具体示例.请编辑您的问题以使用其他澄清细节对其进行更新。鉴于您的问题,我是able to come up with this example,但我不确定它是否真的解决了您的问题。 -
感谢您的浏览!我添加了一个示例来展示我想要的内容!所以我真的需要
New<String>的实现,而不是New<&String>。
标签: rust traits lifetime borrowing