modular-bitfield icon indicating copy to clipboard operation
modular-bitfield copied to clipboard

Getting a reference to sub-struct

Open dali99 opened this issue 4 years ago • 2 comments

I'm not sure how feasible it is, but I would like to implement some functions that take &mut self on my sub-structs

Right now I can only set fields in the main struct via set_foo(), if I want to set a subfield I therefore have to do something like self.set_foo(self.foo().with_bar(true))

instead I would like some way of getting a reference to an object i.e self.foo_ref_mut().set_bar(true)

this would also allow custom functions to be implemented on the substructs that take references rather than making copies.

dali99 avatar Jan 08 '21 07:01 dali99

That's a nice idea!

However, from the current tech stack it is unlikely that conventional references will work here. However, it might be possible to create reference-like types that represent the bitfield struct in a borrowed instead of an owned way and return an instance of this type. This should actually be feasible by extending the codegen of the crate.

Robbepop avatar Jan 08 '21 12:01 Robbepop

This actually would have a lot of added usesbility

One example being accessing a field like some sort of slice-like structure.

struct Foo(B1, B1...)
impl Foo {
    fn index_ref_mut(&self, i: u8) -> RefThing {
        match i {
            0 => self.0_ref_mut(),
            1 => self.1_ref_mut(),
            ...
        }
    }
}

Which would allow changing the fields inside loops and iterators and such. Something i found myself really missing.

dali99 avatar Jan 09 '21 02:01 dali99