Reuse code for mutable and not mutable?

I know this problem is not solved in generic case, but may in my concrete case there is nice work around.

I have two functions:

fn for_each_slice(container: &Container, f: impl FnMut(&[u8])) {

fn for_each_slice_mut(container: &mut Container, f: impl FnMut(&mut [u8])) {

the body of these functions completely the same, except in one case was called Container::get_slice, and in another - Container::get_slice_mut.

Can I solve this problem without code duplication?

I suppose I can use macro_rules! and call this macro from both functions,
but may be there is solution without macros?

1 Like

Then why do you have two distinct functions?

That would depend on what mystery three dots are concealing.

The body of these functions may look the same but that doesn't mean it would use the exact same traits or on-type implementations.

Usually not in a way that's worth it.

But anyway...


The closest you can do is to abstract the entire reference type away, i.e. use a generic non-borrowed T that users of your code can substitute for &mut U or &U as they wish.

However, you will quickly run into limits of this approach, and Rust just doesn't have any good answer to this. Separate _mut versions are the norm. The borrowing rules for shared and exclusive references are quite different, and there's no feature directly unifying them.

Macro can be a good solution Or you can try to call shared/immutable helper functions from the mutable/exclusive version of the function, since you can borrow &mut as &, but not the other way.


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.