gpt4 book ai didi

compiler-errors - 特征方法中的Rust生命周期不匹配

转载 作者:行者123 更新时间:2023-12-02 10:45:01 24 4
gpt4 key购买 nike

我正在研究Rust本书,并尝试实现逻辑以仅允许文本在Post状态下添加到博客Draft中,如here(建议的练习之一)所示。
这个想法是使用结构和特征在Rust中实现状态模式。我只是想将字符串切片传递给add_text的默认实现,如果未处于Draft状态,它将返回一个空字符串切片。然后,我将覆盖Draft状态的默认实现,并返回为Draft状态的文本传递的字符串切片。

pub struct Post {
state: Option<Box<dyn State>>,
content: String,
}

impl Post {
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}

pub fn add_text(&mut self, text: &str) {
let text = self.state.as_ref().unwrap().add_text(text);
// self.state.as_ref().unwrap().add_content(text)
self.content.push_str(text);
}

//snip

trait State {
fn request_review(self: Box<Self>) -> Box<dyn State>;
fn approve(self: Box<Self>) -> Box<dyn State>;
fn content<'a>(&self, post: &'a Post) -> &'a str {
""
}
fn reject(self: Box<Self>) -> Box<dyn State>;
fn add_text(&self, text: &str) -> &str {
""
}
}

struct Draft {}

impl State for Draft {
fn request_review(self: Box<Self>) -> Box<dyn State> {
Box::new(PendingReview {})
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self // don't want to approve a draft before review!
}
fn reject(self: Box<Self>) -> Box<dyn State> {
self // reject doesn't do anything on a draft!
}
fn add_text(&self, text: &str) -> &str {
text
}
}
我在 add_textimpl State for Draft上方的最后一个方法上遇到了生命周期不匹配的问题。该消息显示为:
lifetime mismatch

...but data from `text` is returned hererustc(E0623)
lib.rs(67, 30): this parameter and the return type are declared with different lifetimes...
lib.rs(67, 39):
lib.rs(68, 9): ...but data from `text` is returned here
我是Rust的新手,在这种情况下无法获得有效期注释。我尝试了显式的生命周期注释,但无济于事。另外,我知道由于引用之一是 &self,因此所有生存期参数应自动​​具有与 &self相同的生存期(我认为吗?)。
有人可以启发我来编译此代码吗?这对于将来使用本书的人可能也会很有用。

最佳答案

您被lifetime elision rules绊倒了:

Each elided lifetime in input position becomes a distinct lifetime parameter.

If there is exactly one input lifetime position (elided or not), that lifetime is assigned to all elided output lifetimes.

If there are multiple input lifetime positions, but one of them is &self or &mut self, the lifetime of self is assigned to all elided output lifetimes.

Otherwise, it is an error to elide an output lifetime.


在您的代码 fn add_text(&self, text: &str) -> &str中,返回的 &str继承了 &self的有效期,但实际上它是第二个参数。不匹配,好像是:
fn add_text<'a, 'b>(&'a self, text: &'b str) -> &'a str {
text
}
诀窍是在此处明确显示生命周期:
trait State {
fn add_text<'a>(&'a self, text: &'a str) -> &'a str;
}

impl State for Draft {
fn add_text<'a>(&'a self, text: &'a str) -> &'a str {
text
}
}
如果您想要更通用的版本:
trait State {
fn add_text<'a, 'b: 'a>(&'a self, text: &'b str) -> &'a str;
}

impl State for Draft {
fn add_text<'a, 'b: 'a>(&'a self, text: &'b str) -> &'a str {
text
}
}
这里说只要 text超过 &self都很好。您可以决定是否值得增加额外的通用生命周期。

关于compiler-errors - 特征方法中的Rust生命周期不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59522097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com