【问题标题】:Why does using ? on Result<_, &str> cause a lifetime error?this rust syntax made me feel perplexed
【发布时间】:2022-12-02 03:32:50
【问题描述】:

when i code as follow, the compiler will prompt me

error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> src/byte_packet_buffer.rs:53:51
   |
52 |     fn read_u16(&mut self) -> Result<u16, &str> {
   |                 - let's call the lifetime of this reference `'1`
53 |         let res = ((self.read()? as u16) << 8) | (self.read()? as u16);
   |                     ------------                  ^^^^^^^^^^^ second mutable borrow occurs here
   |                     |
   |                     first mutable borrow occurs here
   |                     returning this value requires that `*self` is borrowed for `'1`

For more information about this error, try `rustc --explain E0499`.
error: could not compile `dns_self` due to previous error
    fn read(&mut self) -> Result<u8, &str> {
        if self.pos >= 512 {
            return Err("End of buffer".into());
        }
        let res = self.buf[self.pos];
        self.pos += 1;

        Ok(res)
    }
    

    fn read_u16(&mut self) -> Result<u16, &str> {
        let res = ((self.read()? as u16) << 8) | (self.read()? as u16);
        Ok(res)
    }

but if i modify the return value from &amp;str to String, everything is ok...

i wanna ask why, any counterexample teach me it is a bug?

but if i modify the return value from &str to String, everything is ok...

【问题讨论】:

    标签: rust lifecycle lifetime


    【解决方案1】:

    Because you did not specify any lifetimes Rust will infer them according to the elision rules to be this:

    fn read<'a>(&'a mut self) -> Result<u8, &'a str>
    

    which means it will infer self to be borrowed for as long as you keep the Result or anything it contained around. To fix it you could just specify the lifetime of the returned str because it's always static anyways.

    fn read(&mut self) -> Result<u8, &'static str>
    

    【讨论】:

    • This "fixes" the symptom but doesn't explain what is really going on. In fact, Rust is being overly restrictive and this example should really be allowed.
    • @PeterHall How did I not explain what's going on? Because of omitted lifetimes rust infers them, this being based on simplistic rules leads to wrong assumptions, fix it by providing correct lifetimes.
    猜你喜欢
    • 2022-12-01
    • 2016-09-21
    • 1970-01-01
    • 2022-12-02
    • 2022-12-01
    • 2022-12-02
    • 2022-09-28
    • 2011-08-01
    • 2011-07-16
    相关资源
    最近更新 更多