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

发布于 2025-01-18 00:52:13 字数 3135 浏览 4 评论 0原文

我敢肯定这是重复的,但是我找不到一个与我的问题相匹配的问题,因为我有几个额外的要求,因为我必须遵守某些无法控制的特征。

这是我的代码。对于那种令人费解的示例,我深表歉意,但这是我尝试使用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);
}

这是我遇到的错误:

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`.

当编译器指出注意:首先,寿命无法超过此处定义的匿名寿命...时,我不知道编译器的含义。这是否意味着某些约束迫使自我不超越方法sometsing_indirect?那没有道理。还有消息使表达式可分配使我感到困惑。 Mainstruct不应分配something_side在调用时不应分配吗?由于我实现了traita,用于mainscrupt的可变引用,因此我不应该以something> mainsstruct的可变引用来调用someways_side通过传递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.

// 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.... Does it mean that some constraint forces self to not outlast the method something_indirect? That makes no sense. Also the message so that the expression is assignable confuses me. MainStruct should not be assigned when something_side is called on it right? 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? Anyways, thanks for the help, and have a great day!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

难以启齿的温柔 2025-01-25 00:52:13

问题是,要使用定义的方法,您必须将mainsstruct借用具有匿名寿命可变的。在您编写的代码中,您不仅在Mainsstruct中借入'a,还借入Mainsstruct本身。这是不必要的,因为借款具有推断的寿命。您可以通过在特质inplant中删除'A来解决此问题

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

,这应该做完全相同的事情,但要删除错误。该错误试图告诉您您编写的代码是错误的,因为它使用结构本身中的寿命借用了Mainsstruct

The trouble is that in order to use the method defined, you must borrow the MainStruct as mutable with an anonymous lifetime. In the code you wrote, you not only borrow the things within MainStruct for 'a, but also MainStruct itself. This is unnecessary since the borrow has an inferred lifetime. You can fix this by removing the 'a in the trait impl

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文