How to make a public struct where all fields are public without repeating `pub` for every field?

Viewed 10824

How can I define a public struct in Rust where all the fields are public without having to repeat pub modifier in front of every field?

A pub_struct macro would be ideal:

pub_struct! Foo {
    a: i32,
    b: f64,
    // ...
}

which would be equivalent to:

pub struct Foo {
    pub a: i32,
    pub b: f64,
    //...
}
1 Answers
macro_rules! pub_struct {
    ($name:ident {$($field:ident: $t:ty,)*}) => {
        #[derive(Debug, Clone, PartialEq)] // ewww
        pub struct $name {
            $(pub $field: $t),*
        }
    }
}

Unfortunately, derive may only be applied to structs, enums and unions, so I don't know how to hoist those to the caller.

Usage:

pub_struct!(Foo {
    a: i32,
    b: f64,
});

It would be nice if I didn't need the parentheses and semicolon, i.e. if Rust supported reader macros.

Related