skip to content

Rust has no constructors, so how should new(), Default and a constructor returning Result divide the work of creating a value?

level: middleimportance: must knowfreq 55%

answer

  1. a convention, not a keyword
  2. the empty value, two spellings
  3. default() cannot fail
  4. validation goes in the return type

basics

~20 s

Constructors are ordinary associated functions: new is the conventional primary one, and Default gives the argument-free value, matching an empty new. When input can be invalid, new returns Result or Option, and the type skips Default unless a valid default exists.

solid answer

~30 s

In Rust a constructor is just an associated function that returns a struct literal. `new` is the convention for the primary one, `with_capacity`-style names mark alternatives, and I/O types use domain names like `File::open`. `Default::default()` is the argument-free value; if a type has a no-argument `new`, it should also implement `Default` with the same behaviour, and Clippy's `new_without_default` lint warns when it does not. Because `default()` returns `Self` and cannot fail, a type that validates its input gets a constructor returning `Result<Self, E>` or `Option<Self>`, like `CString::new` or `NonZero::new`, and implements `Default` only if some valid default exists.

code

rust · 29 lines
rust
#[derive(Debug)]
enum ConfigError {
    ZeroPort,
    NoWorkers,
}

#[derive(Debug)]
struct ServerConfig {
    port: u16,
    workers: usize,
}

impl ServerConfig {
    // No sensible default exists for `port`, so there is no `impl Default`.
    fn new(port: u16, workers: usize) -> Result<Self, ConfigError> {
        if port == 0 {
            return Err(ConfigError::ZeroPort);
        }
        if workers == 0 {
            return Err(ConfigError::NoWorkers);
        }
        Ok(ServerConfig { port, workers })
    }
}

fn main() {
    println!("{:?}", ServerConfig::new(8080, 4));
    println!("{:?}", ServerConfig::new(0, 4));
}

go deeper

for a junior

Recall that new is a naming convention for an associated function, that Default::default() gives an argument-free value, and that a struct literal is what actually builds the value.

for a middle

Explain why Default returns Self and so cannot fail, why that rules Default out for types without a valid default, and how a fallible new with Result or Option replaces it.

for a senior

Show the conventions in code review: new and default() agreeing, the new_without_default lint, with_ names for alternatives, private fields that force construction through the validating function.

for a principal

Weigh what a public Default commits a library to: once released, callers depend on its values, so withholding Default from a type with no safe default is a design decision, not an omission.

## Constructors are just functions Rust has no constructor keyword and nothing runs automatically when a value is created. A value comes from a **struct literal**, `ServerConfig { port, workers }`, and anything that wraps that literal is an ordinary associated function. The Rust API Guidelines (C-CTOR) describe the conventions: - **`new`** is the primary constructor: a static, inherent function (no `self`) on the type, with or without arguments. `Vec::new()` takes none; `Box::new(value)` takes the value to store. - **Domain names** replace `new` where they read better, mostly for I/O resources: `File::open`, `TcpStream::connect`, `UdpSocket::bind`. - **Secondary constructors** add a suffix that says what differs, such as `Vec::with_capacity(n)` and `String::with_capacity(n)`. - **Conversion constructors** start with `from_`, such as `String::from_utf8`; whether to use the `From` trait instead belongs to the material on conversion traits. Because these are plain functions, they can take any arguments, return any type and have any name. That freedom is why the conventions matter: readers expect `new` and look for it first. ## new() and Default should agree `Default` gives a type an argument-free value through `fn default() -> Self`. The guidelines say it is "common and expected" for a type to implement both `Default` and a no-argument `new`, that the two "should have the same behavior", and that either may be written in terms of the other. Clippy enforces the pairing: the **`clippy::new_without_default`** lint, on by default, warns on a public type with `pub fn new() -> Self` and no `Default` impl, and suggests: ```rust impl Default for ServerConfig { fn default() -> Self { Self::new() } } ``` Having both matters in practice: `Default` lets the type sit inside a struct that derives `Default`, appear in `..Default::default()`, and serve calls such as `Option::unwrap_or_default` and `mem::take`, while `new` is what people type. ## When construction can fail `Default::default()` returns `Self`. It has no way to say "there is no valid value", so a type whose invariants rule out any argument-free value should not implement `Default` at all. A constructor that checks its input returns the failure in its type instead: 1. **`Result<Self, E>`** when the caller needs to know what was wrong: `CString::new` returns `Result<CString, NulError>`, and the error reports where the interior nul byte was. 2. **`Option<Self>`** when there is one obvious reason to fail: `NonZero::new` returns `None` only for zero. 3. **`io::Result<Self>`** for constructors that touch the outside world, such as `File::open`. For `ServerConfig`, `fn new(port: u16, workers: usize) -> Result<Self, ConfigError>` rejects a zero port or zero workers and leaves the decision to the caller, who can use `?`, `match` or `expect`. Keeping the fields private stops other modules from bypassing `new` with a literal; the privacy rules themselves belong to the material on visibility. | Shape | Signature | Use it when | |---|---|---| | Plain `new` | `fn new() -> Self` | an argument-free value always exists; pair it with `Default` | | `new` with arguments | `fn new(port: u16) -> Self` | every input value is valid | | Fallible `new` | `fn new(port: u16) -> Result<Self, ConfigError>` | some inputs break an invariant | | `with_` variant | `fn with_capacity(n: usize) -> Self` | a second way to build the same type | | Builder | `ServerConfigBuilder::default()...build()` | many optional settings | ## Writing the constructor itself A few habits keep constructors easy to read and change: - Inside the `impl` block, return `Self` and build with `Self { port, workers }`, so renaming the type touches one line. - Use field init shorthand (`port` instead of `port: port`) when parameters share the fields' names. - Keep `new` cheap and free of side effects; a constructor that opens files or sockets reads better under a domain name such as `open` or `connect`, which tells the reader it does I/O and can fail. ## Common mistakes - Implementing `Default` for a type that has no valid default, so `default()` returns a value that breaks the type's own rules. - Letting `new()` and `default()` drift apart, so the two "empty" values differ. - Panicking inside a constructor on input the caller could reasonably get wrong, which turns a recoverable error into a crash. - Growing `new` to a dozen parameters, at which point a builder reads better. In an interview the strong answer names `new` as a convention rather than a language feature, explains the `new`/`Default` pairing, and shows a fallible `new` returning `Result` for a type that has no default.

  • What does Clippy report for a public type with pub fn new() -> Self and no Default impl?
    The `clippy::new_without_default` lint, which is on by default, warns that you should consider adding a `Default` implementation for the type, and suggests `impl Default for T { fn default() -> Self { Self::new() } }`. The pairing lets the type work in derived `Default` structs, `..Default::default()` and `unwrap_or_default`.
  • Should a validating constructor return Option or Result?
    `Option<Self>` when there is a single, obvious failure, as with `NonZero::new`, which returns `None` only for zero. `Result<Self, E>` when the caller needs to know what failed: `CString::new` returns `NulError`, whose `nul_position()` says where the bad byte was. Several distinct checks, as in a config, point to `Result` with an error enum.

  • new is a keyword the compiler calls automatically when a struct is created.
  • Default::default() can return an error when the value would be invalid.
  • A type with a no-argument new() should not also implement Default.
  • Every type should implement Default, even when a zero value breaks its invariants.