我有以下代码:
//! # 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()
将创建一个拥有的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/