Skip to content

Latest commit

 

History

History
62 lines (47 loc) · 1.28 KB

constructors.md

File metadata and controls

62 lines (47 loc) · 1.28 KB

% Constructors

Define constructors as static, inherent methods. [FIXME: needs RFC]

In Rust, "constructors" are just a convention:

impl<T> Vec<T> {
    pub fn new() -> Vec<T> { ... }
}

Constructors are static (no self) inherent methods for the type that they construct. Combined with the practice of fully importing type names, this convention leads to informative but concise construction:

use vec::Vec;

// construct a new vector
let mut v = Vec::new();

This convention also applied to conversion constructors (prefix from rather than new).

Provide constructors for passive structs with defaults. [FIXME: needs RFC]

Given the struct

pub struct Config {
    pub color: Color,
    pub size:  Size,
    pub shape: Shape,
}

provide a constructor if there are sensible defaults:

impl Config {
    pub fn new() -> Config {
        Config {
            color: Brown,
            size: Medium,
            shape: Square,
        }
    }
}

which then allows clients to concisely override using struct update syntax:

Config { color: Red, .. Config::new() };

See the guideline for field privacy for discussion on when to create such "passive" structs with public fields.