Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[idioms/ctor] adds default constructor section #280

Merged
Prev Previous commit
Next Next commit
fixup! [idioms/ctor] adds default constructor section
replaces fn main examples with rustdoc examples
  • Loading branch information
wookietreiber committed Nov 20, 2021
commit 30519fa2535547df16e306d37784e09f394a7160
38 changes: 24 additions & 14 deletions idioms/ctor.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ Rust does not have constructors as a language construct. Instead, the
convention is to use an associated `new` function to create an object:

```rust
/// Time in seconds.
///
/// # Example
///
/// ```
/// let s = Second::new(42);
/// assert_eq!(42, s.value());
simonsan marked this conversation as resolved.
Show resolved Hide resolved
/// ```
pub struct Second {
value: u64
}
Expand All @@ -15,17 +23,21 @@ impl Second {
Self { value }
}
}

fn main() {
let s = Second::new(42);
}
```

## Default Constructors

Rust supports default constructors with the [`Default`][std-default] trait:

```rust
/// Time in seconds.
///
/// # Example
///
/// ```
/// let s = Second::default();
/// assert_eq!(0, s.value());
/// ```
pub struct Second {
value: u64
}
Expand All @@ -35,26 +47,24 @@ impl Default for Second {
Self { value: 0 }
}
}

fn main() {
let default = Second::default();
assert_eq!(default.value, 0);
}
```

`Default` can also be derived if all types of all fields implement `Default`,
like they do with `Second`:

```rust
/// Time in seconds.
///
/// # Example
///
/// ```
/// let s = Second::default();
/// assert_eq!(0, s.value());
/// ```
#[derive(Default)]
pub struct Second {
value: u64
}

fn main() {
let default = Second::default();
assert_eq!(default.value, 0);
}
```

**Note:** When implementing `Default` for a type, it is neither required nor
Expand Down