Trait `DerefMut` is required but how do I satisfy it through a generic

⚓ Rust    📅 2025-08-09    👤 surdeus    👁️ 5      

surdeus

I am using nightly rust for the Coroutine features

I am trying to write a Coroutine writer that accept AsRef<[u8]> and write it to a file

here is the problematic snippet

struct WriteLinesCoroutine<W: Write>
{
    writer: W
}

impl<W, R> Coroutine<R> for WriteLinesCoroutine<W>
where
    W: Write,
    R: AsRef<[u8]>
{
    type Yield = ();
    type Return = ();

    fn resume(mut self: Pin<&mut Self>, arg: R) -> CoroutineState<Self::Yield, Self::Return> {
        self.writer.write(arg.as_ref());
        CoroutineState::Yielded(())
    }
}

error[E0596]: cannot borrow data in dereference of `Pin<&mut WriteLinesCoroutine<W>>` as mutable
  --> src/main.rs:55:9
   |
55 |         self.writer.write(arg.as_ref());
   |         ^^^^^^^^^^^ cannot borrow as mutable
   |
   = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Pin<&mut WriteLinesCoroutine<W>>`

it says that Pin<&mut WriteLinesCoroutine<W>> doesn't implement DerefMut, I took a look at Pin blanked implementation

looks like &mut WriteLinesCoroutine<W> should implement DerefMut for it to work, but I am not sure why or how to implemented in my case

if I change my generic W for some concrete type, it works fine

impl<R> Coroutine<R> for WriteLinesCoroutine<File>
where
    R: AsRef<[u8]>
{
    ...
}

I am not sure why the compiler accepts File, &mut WriteLinesCoroutine<File> still doesn't implement DerefMut(?), I looked at what traits File implements

doesn't look like File also implements DerefMut so why the compiler accepts it

so I tried to put more constraints on my generic like W: Write + DerefMut but doesn't seem to work either

2 posts - 2 participants

Read full topic

🏷️ Rust_feed