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.
-
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();
-
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);
cargo run --bin static-creation-method
Alice Fisher
John Smith