Methods that promise not to touch some fields?

โš“ Rust    ๐Ÿ“… 2026-02-27    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 1      

surdeus

Was there a proposal for this at some point? For example, in this code below, I check for an optional, and then want to call another mutating method. To do this in current Rust, I believe Iโ€™ll need to clone the thing.

Sometimes I see advice to group fields into sub-structs. But the problem with that is that different methods need different combinations of fields, so there is not one โ€œcorrectโ€ way to partition the fields of your struct.

impl A {
    fn method1(&mut self) {
        if let Some(thing) = &self.optional_thing {
            self.method2(thing); // Not allowed...
        }
    }
    fn method2(&mut self, thing: &Thing) 
        where [I promised not to touch self.optional_thing]
    { 
        ... 
    }   
}

4 posts - 2 participants

Read full topic

๐Ÿท๏ธ Rust_feed