Skip to content

Commit 8f4dfa8

Browse files
committed
Free default() forwarding to Default::default()
When creating default values a trait method needs to be called with an explicit trait name. `Default::default()` seems redundant. A free function on the other hand, when imported directly, seems to be a better API, as it is just `default()`. When implementing the trait, a method is still required.
1 parent 450abe8 commit 8f4dfa8

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

src/libcore/default.rs

+44
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,50 @@ pub trait Default: Sized {
115115
fn default() -> Self;
116116
}
117117

118+
/// Return the default value of a type according to the `Default` trait.
119+
///
120+
/// The type to return is inferred from context; this is equivalent to
121+
/// `Default::default()` but shorter to type.
122+
///
123+
/// For example:
124+
/// ```
125+
/// #![feature(default_free_fn)]
126+
///
127+
/// use std::default::default;
128+
///
129+
/// #[derive(Default)]
130+
/// struct AppConfig {
131+
/// foo: FooConfig,
132+
/// bar: BarConfig,
133+
/// }
134+
///
135+
/// #[derive(Default)]
136+
/// struct FooConfig {
137+
/// foo: i32,
138+
/// }
139+
///
140+
/// #[derive(Default)]
141+
/// struct BarConfig {
142+
/// bar: f32,
143+
/// baz: u8,
144+
/// }
145+
///
146+
/// fn main() {
147+
/// let options = AppConfig {
148+
/// foo: default(),
149+
/// bar: BarConfig {
150+
/// bar: 10.1,
151+
/// ..default()
152+
/// },
153+
/// };
154+
/// }
155+
/// ```
156+
#[unstable(feature = "default_free_fn", issue = "73014")]
157+
#[inline]
158+
pub fn default<T: Default>() -> T {
159+
Default::default()
160+
}
161+
118162
/// Derive macro generating an impl of the trait `Default`.
119163
#[rustc_builtin_macro]
120164
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]

src/test/ui/resolve/issue-2356.stderr

+10-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,16 @@ error[E0425]: cannot find function `default` in this scope
1414
--> $DIR/issue-2356.rs:31:5
1515
|
1616
LL | default();
17-
| ^^^^^^^ help: try: `Self::default`
17+
| ^^^^^^^
18+
|
19+
help: try
20+
|
21+
LL | Self::default();
22+
| ^^^^^^^^^^^^^
23+
help: consider importing this function
24+
|
25+
LL | use std::default::default;
26+
|
1827

1928
error[E0425]: cannot find value `whiskers` in this scope
2029
--> $DIR/issue-2356.rs:39:5

0 commit comments

Comments
 (0)