我有以下代码:
//! # Messages
/// Represents a simple text message.
pub struct SimpleMessage<'a> {
pub user: &'a str,
pub content: &'a str,
}
impl<'a> SimpleMessage<'a> {
/// Creates a new SimpleMessage.
fn new_msg(u: &'a str, c: &'a str) -> SimpleMessage<'a> {
SimpleMessage { user: u,
content: &c.to_string(), }
}
/// Sets a User in a Message.
pub fn set_user(&mut self, u: User<'a>){
self.user = &u;
}
}
但是$ cargo run
返回:
error[E0597]: borrowed value does not live long enough
--> src/messages.rs:34:35
|
34 | content: &c.to_string(), }
| ^^^^^^^^^^^^^ temporary value does not live long enough
35 | }
| - temporary value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 28:1...
|
28 | impl<'a> SimpleMessage<'a> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0597]: `u` does not live long enough
|
54 | self.user = &u;
| ^ borrowed value does not live long enough
55 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 28:1...
--> src/messages.rs:28:1
|
28 | impl<'a> SimpleMessage<'a> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
我试过在函数签名处更改变量的借用格式,但它的内容没有成功,这似乎不是借用问题,但我不太明白,因为生命周期<'a>
定义于 pub struct SimpleMessage<'a>
明确指定其组件的最长使用生命周期,impl<'a> SimpleMessage<'a>
使用相同的生命周期。
我错过了什么?
类似问题: “borrowed value does not live long enough” when using the builder pattern 并不能真正帮助解决这个问题。
最佳答案
str.to_string()
将创建一个 owned String
,它的生命周期不会超过 new_msg
方法,因此您将无法在任何地方传递它的一部分。相反,只需使用 &str
参数,因为它在生命周期 'a
内有效,这正是您所需要的。
/// Creates a new SimpleMessage.
fn new_msg(u: &'a User, c: &'a str) -> SimpleMessage<'a> {
SimpleMessage { user: u, content: c, }
}
另一种方法也有问题。您正在尝试提供拥有的 User
,但 SimpleMessage
结构需要引用。它应该看起来像这样:
/// Sets a User in a Message.
pub fn set_user(&mut self, u: &'a User<'a>){
self.user = u;
}
关于oop - 在 OOP Rust 中,值在构造函数和 setter 中的生命周期不够长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52166060/