首页 > 解决方案 > 值在 OOP Rust 的构造函数和设置器中的寿命不够长

问题描述

我有以下代码:

//! # 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>使用相同的生命周期。

我错过了什么?

类似的问题: 使用构建器模式时“借来的价值不能活得足够长”并 不能真正帮助解决这个问题。

标签: ooprustlifetime

解决方案


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, }
}

另一种方法也有问题。您正在尝试提供 own User,但该SimpleMessage结构需要引用。它应该如下所示:

/// Sets a User in a Message.
pub fn set_user(&mut self, u: &'a User<'a>){
    self.user = u;
}

推荐阅读