Duplicated Code when introducing a new struct variable

So, this may seem to be a 1st world problem but say I have a struct with many fields. Every time I need to introduce a new variable representing the struct, I have to reinitialize everything, and the IDE would just tell me that my codes are duplicated.
Is there any way to initialize the struct efficiently and elegantly (as in not using a function every time like let mut s = create_struct();)?
image

Using a function of a method will be efficient, and is the standard way to avoid repeating struct initialization, or to encapsulate the details of struct initialization. The usual convention is to name the primary constructor Struct::new(), and if there's a reasonable default value, to also implement the Default trait for the struct (which is often as easy as #[derive(Default)]).

1 Like

A usual way to create new structs is by implementing a new() function for them. Which what I think you are hinting at with your create_struct function. See: Methods - Rust By Example

I suspect there is noting inefficient about implementing a new() method. It is likely inlined by the compiler resulting in much the same code as you would get repeating all that structure initialisation manually.

I notice you have initialised your stuct with empty strings for username and password. I presume that means there is no username or password known at the time the struct is created. I suggest you use Option to hold username and password to represent this absence of information:
https://doc.rust-lang.org/rust-by-example/std/option.html

1 Like

If you really don't want a function, you can use struct update syntax and keep a handy-dandy default-like struct instance around to use as a shortcut for initialising other instances.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.