相关疑难解决方法(0)

为什么我不能在同一个结构中存储值和对该值的引用?

我有一个值,我想在我自己的类型中存储该值以及对该值内部内容的引用:

struct Thing {
    count: u32,
}

struct Combined<'a>(Thing, &'a u32);

fn make_combined<'a>() -> Combined<'a> {
    let thing = Thing { count: 42 };

    Combined(thing, &thing.count)
}
Run Code Online (Sandbox Code Playgroud)

有时候,我有一个值,我想在同一个结构中存储该值和对该值的引用:

struct Combined<'a>(Thing, &'a Thing);

fn make_combined<'a>() -> Combined<'a> {
    let thing = Thing::new();

    Combined(thing, &thing)
}
Run Code Online (Sandbox Code Playgroud)

有时,我甚至没有参考该值,我得到同样的错误:

struct Combined<'a>(Parent, Child<'a>);

fn make_combined<'a>() -> Combined<'a> {
    let parent = Parent::new();
    let child = parent.child();

    Combined(parent, child)
}
Run Code Online (Sandbox Code Playgroud)

在每种情况下,我都会收到一个错误,即其中一个值"活不够长".这个错误是什么意思?

lifetime rust borrow-checker

193
推荐指数
3
解决办法
2万
查看次数

“由于需求冲突,无法推断 autoref 的适当生命周期”,但由于特征定义限制,无法更改任何内容

我通过跟踪太多的链接列表来实现链接列表。在尝试实现时iter_mut(),我自己做了并制作了以下代码:

\n
type Link<T> = Option<Box<Node<T>>>;\n\npub struct List<T> {\n    head: Link<T>,\n}\n\nstruct Node<T> {\n    elem: T,\n    next: Link<T>,\n}\n\nimpl<T> List<T> {\n    pub fn iter_mut(&mut self) -> IterMut<T> {\n        IterMut::<T>(&mut self.head)\n    }\n}\n\npub struct IterMut<\'a,  T>(&\'a mut Link<T>);\n\nimpl<\'a, T> Iterator for IterMut<\'a, T> {\n    type Item = &\'a mut T;\n\n    fn next<\'b>(&\'b mut self) -> Option<&\'a mut T> {\n        self.0.as_mut().map(|node| {\n            self.0 = &mut (**node).next;\n            &mut (**node).elem\n        })\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我要避免强制和省略,因为明确可以让我理解更多。

\n

错误:

\n
error[E0495]: cannot infer an appropriate lifetime …
Run Code Online (Sandbox Code Playgroud)

lifetime rust

5
推荐指数
1
解决办法
947
查看次数

如何在不查看代码的情况下读取生命周期错误?

我收到以下生命周期错误:

error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
  --> prusti-viper/src/procedures_table.rs:42:40
   |
42 |         let mut cfg = self.cfg_factory.new_cfg_method(
   |                                        ^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 40:5...
  --> prusti-viper/src/procedures_table.rs:40:5
   |
40 | /     pub fn set_used(&mut self, proc_def_id: ProcedureDefId) {
41 | |         let procedure = self.env.get_procedure(proc_def_id);
42 | |         let mut cfg = self.cfg_factory.new_cfg_method(
43 | |             // method name
...  |
135| …
Run Code Online (Sandbox Code Playgroud)

rust borrow-checker

-2
推荐指数
1
解决办法
158
查看次数

标签 统计

rust ×3

borrow-checker ×2

lifetime ×2