Jared Smith
Jared Smith

Reputation: 21926

Is there shorthand in Rust for declaring a constructor that takes all the members of the struct?

If you have a struct like so:

pub struct Foo {
    pub a: i32,
    pub b: i32,
    pub c: String,
    // and a bunch of other fields
}

Is there any way to declare a constructor that takes the members of the struct without copy/pasting all umpteen field names/types:

impl Foo {
    pub fn new(/* maaaagic */) {

    }
}

or do I have to do

impl Foo {
    pub fn new(
        a: i32,
        b: i32,
        c: String,
        // and a bunch of other args
    ) {

    }
}

Upvotes: 1

Views: 525

Answers (1)

kmdreko
kmdreko

Reputation: 60051

If you are using rust-analyzer, there is a generate new assist that does what you want.

enter image description here

Will generate:

impl Foo {
    pub fn new(a: i32, b: i32, c: String) -> Self { Self { a, b, c } }
}

Upvotes: 6

Related Questions