简体   繁体   English

Rust - 生命周期 - 了解对自身的可变引用的生命周期错误

[英]Rust - Lifetimes - Understanding Lifetime Error for mutable reference to self

I'm sure this is a duplicate, but I can't find a question which matches my question, exactly since I have a couple extra requirements because I have to adhere to some traits that I can't control.我确定这是重复的,但我找不到与我的问题相匹配的问题,正是因为我有一些额外的要求,因为我必须遵守一些我无法控制的特征。

Here is my code.这是我的代码。 I apologize for the sort of convoluted example, but this was the most I could minimize it as I am trying to implement a custom serialization format using the serde library.对于这种令人费解的示例,我深表歉意,但这是我可以最大限度地减少它的次数,因为我正在尝试使用serde库实现自定义序列化格式。

// Doesn't really matter what this struct contains, it just needs an owning method
struct SideStruct;
impl SideStruct {
    fn something_side<A: TraitA>(&self, aval: A) {
        println!("something sideways :)");
        aval.something_a(42)
    }
}

trait TraitA {
    fn something_a(&mut self, data: u32); // this would be the meat of my logic
}

// Note that this struct has an explicit lifetime
struct MainStruct<'a> {
    refr: &'a mut u32
}

// Note that I implement for a mutable reference to MainStruct
impl<'a> TraitA for &'a mut MainStruct<'a> {
    fn something_a(&mut self, data: u32) {
        // Completely arbitrary, can safely ignore this function body
        *self.refr += data;
        println!("We're finally doing something: {}", self.refr);
    }
}

// Implementing for MainStruct itself
impl<'a> MainStruct<'a> {
    // Note, I can't change the signature for this function because it implements a trait
    fn something_indirect(&mut self, ss: &SideStruct) {
        // here is where the error occurs!
        ss.something_side(self)
    }
}

fn main() {
    let mut base_val: u32 = 42;
    let ss = SideStruct {};
    let mut main_val = MainStruct { refr: &mut base_val };
    main_val.something_indirect(&ss);
}

This is the error I got:这是我得到的错误:

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/main.rs:28:27
   |
28 |         ss.something_side(self)
   |                           ^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime defined here...
  --> src/main.rs:27:27
   |
27 |     fn something_indirect(&mut self, ss: &SideStruct) {
   |                           ^^^^^^^^^
note: ...so that the expression is assignable
  --> src/main.rs:28:27
   |
28 |         ss.something_side(self)
   |                           ^^^^
   = note: expected `&mut MainStruct<'a>`
              found `&mut MainStruct<'a>`
note: but, the lifetime must be valid for the lifetime `'a` as defined here...
  --> src/main.rs:26:6
   |
26 | impl<'a> MainStruct<'a> {
   |      ^^
note: ...so that the types are compatible
  --> src/main.rs:28:12
   |
28 |         ss.something_side(self)
   |            ^^^^^^^^^^^^^^
   = note: expected `<&mut MainStruct<'a> as TraitA>`
              found `<&mut MainStruct<'_> as TraitA>`

For more information about this error, try `rustc --explain E0495`.

I don't know what the compiler means when it states that note: first, the lifetime cannot outlive the anonymous lifetime defined here... .我不知道编译器在声明该note: first, the lifetime cannot outlive the anonymous lifetime defined here... Does it mean that some constraint forces self to not outlast the method something_indirect ?这是否意味着某些约束迫使 self 不能比方法something_indirect更持久? That makes no sense.这是没有意义的。 Also the message so that the expression is assignable confuses me.此外so that the expression is assignable的消息也让我感到困惑。 MainStruct should not be assigned when something_side is called on it right?当调用something_side时不应该分配MainStruct对吧? Since I implemented TraitA for a mutable reference to MainStruct , shouldn't I be able to call something_side with a mutable reference to MainStruct by passing self ?由于我为TraitA的可变引用实现了MainStruct ,难道我不能通过传递self来调用带有对MainStruct的可变引用的something_side吗? Anyways, thanks for the help, and have a great day!无论如何,感谢您的帮助,祝您有美好的一天!

The trouble is that in order to use the method defined, you must borrow the MainStruct as mutable with an anonymous lifetime.问题在于,为了使用定义的方法,您必须借用MainStruct作为具有匿名生命周期的可变对象。 In the code you wrote, you not only borrow the things within MainStruct for 'a , but also MainStruct itself.在您编写的代码中,您不仅为'a借用了MainStruct中的内容,而且还借用了MainStruct本身。 This is unnecessary since the borrow has an inferred lifetime.这是不必要的,因为借用具有推断的生命周期。 You can fix this by removing the 'a in the trait impl您可以通过删除 trait impl中的'a来解决这个问题

impl<'a> TraitA for &mut MainStruct<'a> {
    /*...*/
}

This should do the exact same thing, but removes the bug.这应该做完全相同的事情,但消除了错误。 The bug is trying to tell you that the code you wrote is buggy, because it borrows MainStruct using a lifetime in the struct itself.该错误试图告诉您您编写的代码有错误,因为它在结构本身中使用生命周期借用了MainStruct

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何解决生存期错误以在Rust中进行可变引用? - How to resolve lifetime error for mutable reference in Rust? 使用可变的“self”引用调用方法时的生命周期错误 - lifetime error when calling method with mutable `self` reference Rust字符串生存期和迭代器适配器(生存期编译错误) - Rust string lifetimes and iterator adapters (lifetime compile error) Rust,在迭代中需要一个可变的 Self 引用 - Rust, need a mutable reference of Self inside iteration 了解生命周期:最大生命周期和“静态” - Understanding lifetimes: max lifetime and 'static Rust 生命周期的问题:impl 使用匿名生命周期,function 使用 &lt;'a&gt;,更改生命周期以匹配会导致错误 - Trouble with Rust lifetimes: impl uses anonymous lifetime and function uses <'a>, changing the lifetimes to match leads to an error 闭包的常量数组,在Rust中使用寿命参数对结构进行可变引用 - Const array of closures taking a mutable reference to a struct with lifetime parameter in Rust 了解Rust中参数化结构的生命周期 - Understanding lifetimes for parameterized structs in Rust 从具有自链接生命周期的可变引用获取不可变引用时有什么区别? - What are the differences when getting an immutable reference from a mutable reference with self-linked lifetimes? 理解这个 Rust 生命周期示例 - Understanding of this Rust lifetime example
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM