Pattern for function that takes &mut but returns const ref

⚓ Rust    📅 2025-04-27    👤 surdeus    👁️ 8      

surdeus

Warning

This post was published 116 days ago. The information described in this article may have changed.

I'm looking for an elegant pattern to express an operation that performs a mutation, but then downgrades the reference to an immutable reference when the mutation is complete.

Along the lines of this:

struct S {
    f0: usize,
    f1: usize,
}

impl S {
    fn mutate_and_reference(&mut self) -> &usize {
        self.f0 += 42;

        //In real code, the return ref is expensive to calculate,
        // but is free as a side-effect of the mutate part
        &self.f0
    }
    fn do_something_else(&self, arg: &usize) -> usize {
        self.f1 + *arg
    }
}

fn main() {
    let mut s = S{f0: 0, f1: 0};
    let arg = s.mutate_and_reference();
    let _val = s.do_something_else(arg);
}

I'd normally tackle this by having mutate_and_reference actually return some intermediate data with a 'static lifetime, and then re-borrow s as const, computing a const reference to s using that intermediate data.

However, I'm wondering if there is a nicer way to "downgrade" a &mut reference to a const & reference.

Thank you for any thoughts.

2 posts - 2 participants

Read full topic

🏷️ rust_feed