Skip to content

Expressing variant lifetimes with trait objects is tricky #42984

@aidanhs

Description

@aidanhs

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions