rust-protobuf icon indicating copy to clipboard operation
rust-protobuf copied to clipboard

Generate a constructor containing all fields

Open mverleg opened this issue 6 years ago • 0 comments

Using new gives an uninitialized object, and the standard Rust constructor with MyType { ... } needs one to include or 'derive' the unknown_fields and cached_size.

According to this page there's a convention to call such a method with_more_details since new is taken.

The main advantage would be that one can't forget a field, and one gets informed by the compiler if a new field is added that you don't initialize.

The generated code would be something like this:

#[derive(PartialEq, Clone, Default)]
pub struct Like {
    // message fields
    pub is_liked: bool,
    pub ts_changed: ::protobuf::SingularPtrField<::protobuf::well_known_types::Timestamp>,
    // special fields
    pub unknown_fields: ::protobuf::UnknownFields,
    pub cached_size: ::protobuf::CachedSize,
}

impl Like {
    pub fn new() -> Like {
        ::std::default::Default::default()
    }

    pub fn with_more_details(is_liked: bool, ts_changed: ::protobuf::SingularPtrField<::protobuf::well_known_types::Timestamp>) -> Self {
        Like {
            is_liked,
            ts_changed,
            ..Like::new()
        }
    }
    
    // ...
}

mverleg avatar Jun 07 '19 21:06 mverleg