Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expressing variant lifetimes with trait objects is tricky #42984

Closed
aidanhs opened this Issue Jun 30, 2017 · 1 comment

Comments

Projects
None yet
1 participant
@aidanhs
Copy link
Member

aidanhs commented Jun 30, 2017

https://is.gd/xCZ1UF

use std::io::{Cursor, Read, Write};

trait Ser<W> {
    fn serialize<'a, 'b>(&'a self, writer: &'b mut W);
}

fn main() {
    let mut buffer = vec![0u8];
    let frameworks: Vec<&Ser<Cursor<&mut [u8]>>> = vec![];

    for framework in frameworks {
        let mut write_cursor = Cursor::new(buffer.as_mut_slice());
        framework.serialize(&mut write_cursor);
    }
}

This does not compile with:

rustc 1.20.0-nightly (3bfc18a96 2017-06-29)
error[E0499]: cannot borrow `buffer` as mutable more than once at a time
  --> <anon>:12:44
   |
12 |         let mut write_cursor = Cursor::new(buffer.as_mut_slice());
   |                                            ^^^^^^
   |                                            |
   |                                            second mutable borrow occurs here
   |                                            first mutable borrow occurs here
...
15 | }
   | - first borrow ends here

error: aborting due to previous error(s)

But changing it to a struct with an impl works - https://is.gd/2OM3ud

Is there a way to express this? I've been fighting with it for a little while, so if there is I suspect there could be some diagnostic improvements.

@aidanhs

This comment has been minimized.

Copy link
Member Author

aidanhs commented Jun 30, 2017

Ah, changing it to let frameworks: Vec<&for<'r> Ser<Cursor<&'r mut [u8]>>> = vec![]; works (thanks to @Twey). Which makes sense.

@aidanhs aidanhs closed this Jun 30, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.