oop - 值在 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>
使用相同的生命周期。
我错过了什么?
类似的问题: 使用构建器模式时“借来的价值不能活得足够长”并 不能真正帮助解决这个问题。
解决方案
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;
}
推荐阅读
- quickbooks - 各站点的 QODBC 程序集库存
- node.js - Azure Node.js Linux 应用服务 Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException:请求正文太大
- python - 为什么 queryset[0] 和 queryset.first() 返回不同的记录?
- c++ - C++ 程序如何为插入 (<<) 运算符选择正确的函数?
- vue.js - Vuex 对象在 Vue 组件中显示为 Null
- c# - 如何在 dotnet core 中为 HttpClient 指定 HTTP/2“先验知识”模式?
- json - Swift JSON 撇号'字符串在 Web 服务器上被奇怪地解释
- pandas - 将文件夹中的 *random* csv 文件导入 pandas
- google-api - Google Indexing API - 权限被拒绝。无法验证 URL 所有权
- javascript - 在 React Native JSX 中从 2D 数组渲染项目