rust - 具有引用和引用返回的结构:由于需求冲突,无法推断出 autoref 的适当生命周期
问题描述
在下面的代码中,我了解到在返回的引用Storage::insert
和Consumer<'a>
. 但是,我遇到了麻烦:
理解为什么会发生这种冲突——也就是说,两者
Consumer::storage
都有Consumer::current_value
相同的生命周期,那么 Rust 推断出的其他生命周期是什么?<'a>
如何最好地指定生命周期以及为什么这样做
struct Storage {
value: i64,
}
impl Storage {
fn new() -> Self {
Storage { value: 0 }
}
fn insert(&mut self, v: i64) -> &i64 {
self.value = v;
&self.value
}
}
struct Consumer<'a> {
storage: &'a mut Storage,
current_value: &'a i64,
}
impl<'a> Consumer<'a> {
fn new(s: &'a mut Storage) -> Self {
Consumer {
storage: s,
current_value: &s.value,
}
}
fn new_value(&mut self, v: i64) {
self.current_value = self.storage.insert(v);
}
}
此代码导致的错误是:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src/lib.rs:30:43
|
30 | self.current_value = self.storage.insert(v);
| ^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 29:5...
--> src/lib.rs:29:5
|
29 | / fn new_value(&mut self, v: i64) {
30 | | self.current_value = self.storage.insert(v);
31 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:30:30
|
30 | self.current_value = self.storage.insert(v);
| ^^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 21:6...
--> src/lib.rs:21:6
|
21 | impl<'a> Consumer<'a> {
| ^^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:30:30
|
30 | self.current_value = self.storage.insert(v);
| ^^^^^^^^^^^^^^^^^^^^^^
我已阅读以下内容,但不确定我是否遵循它们如何适用于我的问题(也许他们这样做了,而我只是没有正确阅读):
解决方案
推荐阅读
- json - 尝试运行 npm run dev “未找到条目。”
- android - 向用户显示 ArrayList
- c# - 如何获取DLL中调用的静态方法的所有参数并保存到资源文件
- scala - scala - 如何为期货、并行收集和 akka 创建共享线程池/执行上下文
- three.js - 如何获取 TubeBufferGeometry 路径中的点索引?(三.js)
- perl - 使用 Chart::Gnuplot Perl 的热图
- java - 使用 OAuth2RestTemplate 在 Rest Api 调用中出现异常或错误后继续
- c# - 在客户端和服务器之间进行 2 个请求的正确方法
- c# - 解决方案c#中的单个配置设置文件
- spring-data-jdbc - 使用 Azure SQL Server 保存聚合根时出现 DataRetrievalFailureException