On using mutable refernces in getting data

I have trait I am working on that looks like this

trait GetTextureData {
    fn texture_data_dim(&self, width: &mut u32, height: &mut u32, length: &mut u32);
    fn texture_data(&self) -> Vec<u8>;
}

It's part of a Strategy design pattern.

My question is around the use of mutable references in texture_data_dim. texture_data_dim would not feel out of place to me in the C world, but my inclination is to return a struct or tuple. Am I making mountains out of mole hills or is this not a good use cases for using mutable reference?

I would appreciate anyone's thoughts and/or materials documenting good use cases of mutable references.

A getter that mutates its arguments would be a very odd design choice, to put it mildly. I would return a struct that clearly indicates which value is for width, which for height and which for length.

I usually use mutable arguments when I need the caller to keep the ownership of the structure to be mutated or want to avoid unnecessary allocations, i.e. usually a collection (HashMap, Vec) or a String.

2 Likes

Rust is eager to inline methods (which you can help with the #[inline] attribute), so returning a struct with dimensions is likely to compile to the same code as returning values via mutable arguments.

In Rust it's more idiomatic to use functional style and return new values instead of mutating, unless the cost would be too big (bit for u32 it's not, and using a reference to u32 can be more costly than copying u32 itself).

1 Like