I’m using Tokio to implement a server that write to a file. Problem with code below is that to write to a file, it has to be &mut and hence the &mut self in insert, set functions but the call method in tokio_service.Service interface requires call to have &self parameter. and that’s the error coming from running that code error[E0596]: cannot borrow immutable borrowed content as mutable

Write::write(&mut self, ...) means Self (ie whatever type you’re implementing Write for) is borrowed mutably. Self is &File here so you end up with &mut &File. Since any immutable reference is Copy it means you can have as many &File values floating around as you want and you can borrow each mutably (since all uses of it have their own copy, so to speak).

We want to get a &Filetype so we can borrow it mutably for the call to write (see my previous reply). Since the dot operator auto-derefs, self.handler gives us a File, not a &File. (&self.handler).write(...) forces the type to (temporarily, if you will) become &File and that’s the type we end up calling write on (which is what we want).

I’ve made a sample implementation to understand what you said, but it seems it’s also refuses to build and I used the same trick in storage.set. I don’t get why it worked with File but didn’t work here

This code requires that you have a mutable borrow of self (i.e. Index) to call insert. But set only has an immutable borrow of Storage, and since Storage owns the Index, it has only an immutable borrow of Index as well.

Most types in Rust will require a &mut to perform mutation, such as this case where you have a Vec<u32> at the “bottom” of the call chain - it does not allow mutation without having a mutable reference to it.

File is special in that there’s an implementation of mutable APIs for &File. This is allowed because the underlying OS file operations already provide the required guarantees that allow writes to it across aliasing references. The analogous here would be if Vec::push was defined as pub fn push(&self, item: T) ..., but that doesn’t exist because a Vec does not support aliasing mutation (i.e. mutation from multiple shared references).