about summary refs log tree commit diff
path: root/src/libcore
diff options
context:
space:
mode:
authorRalf Jung <post@ralfj.de>2020-06-08 09:55:31 +0200
committerGitHub <noreply@github.com>2020-06-08 09:55:31 +0200
commit244465dbb8b0e49d741bc1f93925d037020cb1f1 (patch)
treee85257ee148436d1fb8388c0e032dcfed719aebe /src/libcore
parent824ea6bf2d883fd04ed826f1d09a20dc3ede11d0 (diff)
parentebb8722ea7b184ade7015fd1094475a18e1198f7 (diff)
Rollup merge of #73001 - ilya-bobyr:master, r=dtolnay
Free `default()` forwarding to `Default::default()`

It feels a bit redundant to have to say `Default::default()` every time I need a new value of a type that has a `Default` instance.
Especially so, compared to Haskell, where the same functionality is called `def`.
Providing a free `default()` function that forwards to `Default::default()` seems to improve the situation.
The trait is still there, so if someone wants to be explicit and to say `Default::default()` - it still works, but if imported as `std::default::default;`, then the free function reduces typing and visual noise.
Diffstat (limited to 'src/libcore')
-rw-r--r--src/libcore/default.rs44
1 files changed, 44 insertions, 0 deletions
diff --git a/src/libcore/default.rs b/src/libcore/default.rs
index 06402a05d26..9a8d65cd4e0 100644
--- a/src/libcore/default.rs
+++ b/src/libcore/default.rs
@@ -115,6 +115,50 @@ pub trait Default: Sized {
     fn default() -> Self;
 }
 
+/// Return the default value of a type according to the `Default` trait.
+///
+/// The type to return is inferred from context; this is equivalent to
+/// `Default::default()` but shorter to type.
+///
+/// For example:
+/// ```
+/// #![feature(default_free_fn)]
+///
+/// use std::default::default;
+///
+/// #[derive(Default)]
+/// struct AppConfig {
+///     foo: FooConfig,
+///     bar: BarConfig,
+/// }
+///
+/// #[derive(Default)]
+/// struct FooConfig {
+///     foo: i32,
+/// }
+///
+/// #[derive(Default)]
+/// struct BarConfig {
+///     bar: f32,
+///     baz: u8,
+/// }
+///
+/// fn main() {
+///     let options = AppConfig {
+///         foo: default(),
+///         bar: BarConfig {
+///             bar: 10.1,
+///             ..default()
+///         },
+///     };
+/// }
+/// ```
+#[unstable(feature = "default_free_fn", issue = "73014")]
+#[inline]
+pub fn default<T: Default>() -> T {
+    Default::default()
+}
+
 /// Derive macro generating an impl of the trait `Default`.
 #[rustc_builtin_macro]
 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]