Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,
    //...
}
like image 665
Petrus Theron Avatar asked Dec 20 '18 10:12

Petrus Theron


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.

like image 103
Petrus Theron Avatar answered Oct 08 '22 06:10

Petrus Theron