Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#[derive(StructGetMutField)] to get field without specifying the field name #19

Closed
nielsle opened this issue Aug 8, 2016 · 0 comments
Closed

Comments

@nielsle
Copy link

nielsle commented Aug 8, 2016

Here is another idea that might be useful. It could be nice to have a generic macro to get a field without specifying the field name

�struct A;
struct B;

#[derive(StructGetMutField)]
struct Foo {
    a:A,
    b:B,
}

fn main() {
    let foo= Foo {a:A, b:B};
    let _a: &A = foo.get_mut_field();
    let _b: &B = foo.get_mut_field();
}

The following could be derived behind the scenes

trait GetMutField<T>   {
    fn get_mut_field(&mut self) ->&mut T;
}

impl GetMutField<A> for Foo {
    fn get_mut_field(&mut self) ->&mut A {&mut self.a}
}

impl GetMutField<B> for Foo {
    fn get_mut_field(&mut self) ->&mut B {&mut self.b}
}

This macro would allow me to do the following with minimal boiler plate code;

#[derive(StructGetMutField)]
struct Foo {
    as:Vec<A>,
    bs:Vec<B>,
}

let mut foo = Foo {as:Vec::new(), bs:Vec::new(), };
let a = A;
foo.get_mut_field().push(a);

Similarly it would allow me to create a poor mans TypeMap without using the Any-trait.

#[derive(StructGetMutField)]
struct Foo {
    a_opt:Option<A>,
    b_opt:Option<B>,
}

let mut foo = Foo {a_opt: Option::new(), b_opt: Option::new(), };
foo.get_mut_field() = Some(A);;
DanielKeep added a commit that referenced this issue Sep 22, 2017
Contains `StructNew`, `StructTypeIndex`, and `StructTypeIndexMut`.

Closes #19.
@nielsle nielsle closed this as completed Sep 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant