nrc / derive-new

derive simple constructor functions for Rust structs
MIT License
525 stars 35 forks source link

#[derive(new)] on non-pub struct should give `fn new` the right visibility (required for 2018 idioms) #40

Open wycats opened 6 years ago

wycats commented 6 years ago

Today, #[derive(new)] always creates a pub fn, regardless of the visibility of the struct it's applied to.

In Rust 2018, that becomes a lint error, which makes it (at present) difficult to use this crate in a crate with #[warn(rust_2018_idioms)].

Instead, the visibility of the new method should be the same as the visibility of the struct.

It might also be useful to allow the visibility to be controlled directly. Straw man:

#[derive(new)]
#[new(visibility = crate)]
struct Point {
    x: u32,
    y: u32,
}
Boscop commented 5 years ago

Yes, please allow making new private even for public structs/enums. In several of my use cases I only intend to call the derived new internally, and I get this error:

error: private type in public interface. can't leak private type

Because the derived new takes as arg a private type, to initialize a private member.

JarrettBillingsley commented 3 years ago

I've run into this, and now (since this is a relatively recent Rust feature) with wanting a const fn new.

wycats commented 3 years ago

I still think this is a good idea, even though the original annoying issue is no longer the root cause of the problem.