otoomey
otoomey

Reputation: 999

Can you specify return type mutability in Rust?

Is it possible to specify the mutability of the assigned variable in rust? Something like

fn new(len: usize) -> Thing { ... }
fn new_mut(len: usize) -> mut Thing { ... }

I have a specific case where knowing the mutability of a type can be used to make several optimizations under the hood for my data structure.

Trying to enforce mutability manually is possible, but seems quite inelegant, especially when the concept of mutability is an intrinsic part of the rust language already. And you end up in weird situations like this:

// Thing::new() returns a data structure with an immutable backing type, 
// but the code below looks like it should be mutable.
let mut foo = Thing::new(5);

In this case, I either have to choice of trying to figure out if someone tried to make a mutable reference to my immutable Thing manually (and panicking I suppose), or by making new return a wrapper over Thing that hides all mutable functions (which means the mut keyword is rendered pointless and misleading).

Upvotes: 3

Views: 1460

Answers (1)

Zólyomi István
Zólyomi István

Reputation: 2441

I think you have some misconception: mutability of a return type is not and should NOT be part of the function signature, mutability is always decided on the caller side.

The return type is a description of the memory slot returned to the caller when the call stack returns after executing the function. Ownership of the returned type is fully transferred, e.g. a Thing is fully moved to the caller. How the caller handles the returned memory cell is not the concern of the called function because it's already finished and returned. There's no such thing as mutable or immutable return type, mutability is always related to memory slots. In your example this is only decided at declaring variable foo that defines the memory slot of the result type on the caller side. As long as you have full ownership of a data structure, you're free to decide or even change mutability of the data.

What you're looking for is maybe a separate type specialized for optimization.

Upvotes: 10

Related Questions