about summary refs log tree commit diff
diff options
context:
space:
mode:
authorIlya Bobyr <ilya.bobyr@gmail.com>2020-06-03 20:36:53 -0700
committerIlya Bobyr <ilya.bobyr@gmail.com>2020-06-07 01:27:06 -0700
commit8f4dfa88399320eba07e9717f60a5c32d73299a3 (patch)
treeedd1613f6fff1759b648b42a23f0d8af00256823
parent450abe80f193ccefbfcd48214d70520f2d507f0e (diff)
downloadrust-8f4dfa88399320eba07e9717f60a5c32d73299a3.tar.gz
rust-8f4dfa88399320eba07e9717f60a5c32d73299a3.zip
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.
-rw-r--r--src/libcore/default.rs44
-rw-r--r--src/test/ui/resolve/issue-2356.stderr11
2 files changed, 54 insertions, 1 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")]
diff --git a/src/test/ui/resolve/issue-2356.stderr b/src/test/ui/resolve/issue-2356.stderr
index 329543114a6..b687f0b0af0 100644
--- a/src/test/ui/resolve/issue-2356.stderr
+++ b/src/test/ui/resolve/issue-2356.stderr
@@ -14,7 +14,16 @@ error[E0425]: cannot find function `default` in this scope
   --> $DIR/issue-2356.rs:31:5
    |
 LL |     default();
-   |     ^^^^^^^ help: try: `Self::default`
+   |     ^^^^^^^
+   |
+help: try
+   |
+LL |     Self::default();
+   |     ^^^^^^^^^^^^^
+help: consider importing this function
+   |
+LL | use std::default::default;
+   |
 
 error[E0425]: cannot find value `whiskers` in this scope
   --> $DIR/issue-2356.rs:39:5