Mutability In APIs

Hi everyone,

I'm still getting my head around rust a bit. Its a bit of a rollercoaster.

Here is my latest dilemma which I'm sure is a general problem.

I have a program which is for converting between different storage systems. Right now it could be an sqlite file which we want to write the contents to postgres. There could also be a http server in the future.

So I created a LogWriter and LogReader trait to cover the use cases with various methods borrowing self. Logically I thought - they aren't logically changing the structure - just causing side effects in files etc.

I started with the sqlite reader and that all worked well. Now I'm trying to do the postgres writer and I've hit a snag.

The postgres methods require a mutable borrow to execute. So do I go back and make the trait borrow mutable? Or should I use some sort of interior mutability?

I think it makes sense for the trait to borrow mutably. An external side effect seems as important as an internal one to control. But is there a general course of action to follow here? If I had got further and found this it would have meant a breaking change to all trait implementations so should you just start with &mut self unless the method is an obvious getter?

1 Like

The question you need to ask is not "does the operation mutate anything?" (whatever that means), but rather "does the operation require exclusive access?". In your case, the sqlite library requires exclusive access for you to write to it, so you should probably require exclusive access too.


Thanks @alice. Thats a much simpler way to think about it!

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.