oop - 在 OOP Rust 中,值在构造函数和 setter 中的生命周期不够长

标签 oop rust lifetime

我有以下代码:

//! # 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/

相关文章:

php - 我应该还是不应该使用 getter 和 setter 方法?

java - 调用父类(super class)型方法会创建一个新的父类(super class)型对象吗?

rust - 如何在 Rust 中解构和取消引用元组

rust - 如何快速查看HashSet中的任意值?

static - 为什么在同一范围内可以有多个具有静态生命周期的可变引用

data-structures - 我可以在没有所有者移动或不安全的情况下遍历单向链表吗?

c# - 运算符和继承

php - fatal error :调用未定义的方法 dbconnection::prepare()

rust - 为什么不使用 Option unwrap move 值?

scope - 为什么泛型生命周期不符合嵌套范围的较小生命周期?