concept new() in category rust

appears as: new()
Rust in Action

This is an excerpt from Manning's book Rust in Action.

Listing 2. 5 introduces some new Rust. It demonstrates two forms of initializing non-primitive data types. One is a literal syntax provided by the Rust language (line 4). The other is the new() static method that many types implement for added convenience (line 5). A static method is a function that’s available from a type, not an instance of that type.[6]

Listing 2. 5. Calculating values with complex numbers. Demonstrates accessing a third party crate (num), calling a type’s new() method and accessing fields with the dot operator (.). (ch2/ch2-complex/src/main.rs)
use num::complex::Complex;                   #1

fn main() {
  let a = Complex { re: 2.1, im: -1.2 };      #2
  let b = Complex::new(11.1, 22.2);           #3
  let result = a + b;

  println!("{} + {}i", result.re, result.im)  #4
}

3.3.1. Simplifying object creation by implementing a new() method

Creating objects with reasonable defaults is done through the new() method.

Using new() is a convention within the Rust community. Unlike other languages, new is not a keyword and isn’t given some sort of blessed status above other methods.

Table 3. 1. Comparing Rust’s literal syntax for creating objects with the use of new() methods

Current

With File::new()

File {
    name: String::from("f1.txt"),
    data: Vec::new(),
};
File::new("f1.txt", vec![]);
File {
  name: String::from("f2.txt"),
  data: vec![114, 117, 115, 116, 33],
};
File::new("f2.txt", vec![114, 117, 115, 116, 33]);