Skip to content

Latest commit

 

History

History

static-creation-method

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

Static Creation Method

Static Creation Method is an associated function that returns a new object which is usually an instance of that particular type.

There is a notion of "constructor" in a typical OOP language which is a default class method to create an object. Not in Rust: constructors are thrown away because there is nothing that couldn't be achieved with a static creation method.

💡 See The Easiest Patterns in Rust. See also Factory Comparison.

There are a few ways to define a static creation method.

  1. A default() method from Default trait for construction with no parameters. Use either default #[derive(Default)], or a manual trait implementation.

    #[derive(Default)]
    struct Circle;
    
    let circle = Circle::default();
  2. A handwritten new() method for a custom object creation with parameters:

    impl Rectangle {
        pub fn new(width: u32, length: u32) -> Rectangle {
            Self { width, length }
        }
    }
    
    let rectangle = Rectangle::new(10, 20);

How to Run

cargo run --bin static-creation-method

Output

Alice Fisher
John Smith