DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Data Engineering
  3. Data
  4. Another Way of Creating struct Instances in Rust

Another Way of Creating struct Instances in Rust

Follow along to learn a new way to create struct instances in Rust.

Ayush Mishra user avatar by
Ayush Mishra
·
May. 06, 19 · Tutorial
Like (1)
Save
Tweet
Share
10.01K Views

Join the DZone community and get the full member experience.

Join For Free

Until now, I knew of only one way to create an instance of struct, which is mentioned in Rust’s official programming book — by adding curly brackets after the name of the struct and adding key-value pairs inside the curly brackets like below.

struct Book {
    title: String,
    author: String,
    genres: String,
    pages: u32,
}
let book = Book {
        title: String::from("Hey "),
        author: String::from("abc"),
        genres: "Fiction".to_string(),
        pages: 150,
    };


I explored another way of doing this using derive-new. This will add an impl fn new(…) -> Self method generated from the struct's attribute, which will create an instance of the struct.

Let’s create the above struct Book using derive-new. To use this,

  • Add a dependency in Cargo.toml
[dependencies]
derive-new = "0.5"
  • Include the macro
#[macro_use]
extern crate derive_new;
#[derive(new)]
struct Book {
    title: String,
    author: String,
    genres: String,
    pages: u32,
}


The #[derive(new)] line invokes a procedural macro in that crate, which generates code like:

impl Book {
    fn new(title_value: String, author_value: String, genres_value: String, pages_value: u32) -> Bar {
        Book { title: title_value, author: author_value, genres: genres_value, pages: pages_value }
    }
}


You can create an instance of Book.

#[test]
fn test_book() {
    let common_book = Book::new(
        String::from("Common"),
        String::new(),
        String::from("Programming"),
        100,
    );
    assert_eq!(
        common_book,
        Book {
            title: String::from("Common"),
            author: String::new(),
            genres: "Programming".to_string(),
            pages: 100
        }
    );
}


I am from a Scala background and I think of Rust’s struct as Scala’s case class, so another advantage of using #[derive(new)] is that we can set default values for struct variables. Default values can be specified either using the #[new(default)] attribute, which removes the argument from the constructor, or #[new(value = "..")]. Let’s see an example.

#[macro_use]
extern crate derive_new;

#[derive(Debug, new, PartialEq)]
struct Book {
    title: String,
    #[new(default)]
    author: String,
    #[new(value = r#""Programming".to_string()"#)]
    genres: String,
    #[new(value = "100")]
    pages: u32,
}

#[test]
fn test_book() {
    let common_book = Book::new(String::from("Common"));
    assert_eq!(
        common_book,
        Book {
            title: String::from("Common"),
            author: String::new(),
            genres: "Programming".to_string(),
            pages: 100
        }
    );
}


Now all those arguments (for example: author, genres, pages), whose values have been set as default, will be removed from the new function. You can create the instance of Book only from titles, as you can see in the above example.

Now what will happen if you pass all the parameters in a new function? Let’s see:

let another_book = Book::new(String::from("Hey"), String::from("abc"), "Fiction".to_string(), 150);


You will get a compilation error.

 error[E0061]: this function takes 1 parameter but 4 parameters were supplied
  --> src/main.rs:51:24
   |
4  | #[derive(Debug, new, PartialEq)]
   |                 --- defined here
...
51 |     let another_book = Book::new(String::from("Hey"), String::from("abc"), "Fiction".to_string(), 150);
   |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected 1 parameter

error: aborting due to previous error

For more information about this error, try `rustc --explain E0061`.
error: Could not compile `variables`.


You can now use the traditional way if you want to create a Book instance with different parameters.

    let another_book = Book {
        title: String::from("Hey "),
        author: String::from("abc"),
        genres: "Fiction".to_string(),
        pages: 150,
    };


derive-new is helpful when you want to create a struct instance with default values. I hope you enjoyed reading this blog.

Data structure Rust (programming language)

Published at DZone with permission of Ayush Mishra. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Accelerating Enterprise Software Delivery Through Automated Release Processes in Scaled Agile Framework (SAFe)
  • How to Use Java Event Listeners in Selenium WebDriver?
  • 5 Common Firewall Misconfigurations and How to Address Them
  • The Beauty of Java Optional and Either

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: