pub trait Default: Sized {
// Required method
fn default() -> Self;
}Expand description
A trait for giving a type a useful default value.
Sometimes, you want to fall back to some kind of default value, and
don’t particularly care what it is. This comes up often with structs
that define a set of options:
struct SomeOptions {
foo: i32,
bar: f32,
}How can we define some default values? You can use Default:
#[derive(Default)]
struct SomeOptions {
foo: i32,
bar: f32,
}
fn main() {
let options: SomeOptions = Default::default();
}Now, you get all of the default values. Rust implements Default for various primitive types.
If you want to override a particular option, but still retain the other defaults:
fn main() {
let options = SomeOptions { foo: 42, ..Default::default() };
}§Derivable
This trait can be used with #[derive] if all of the type’s fields implement
Default. When derived, it will use the default value for each field’s type.
§enums
When using #[derive(Default)] on an enum, you need to choose which unit variant will be
default. You do this by placing the #[default] attribute on the variant.
#[derive(Default)]
enum Kind {
#[default]
A,
B,
C,
}You cannot use the #[default] attribute on non-unit or non-exhaustive variants.
The #[default] attribute was stabilized in Rust 1.62.0.
§How can I implement Default?
Provide an implementation for the default() method that returns the value of
your type that should be the default:
enum Kind {
A,
B,
C,
}
impl Default for Kind {
fn default() -> Self { Kind::A }
}§Examples
#[derive(Default)]
struct SomeOptions {
foo: i32,
bar: f32,
}Required Methods§
1.0.0 (const: unstable) · Sourcefn default() -> Self
fn default() -> Self
Returns the “default value” for a type.
Default values are often some kind of initial value, identity value, or anything else that may make sense as a default.
§Examples
Using built-in default values:
let i: i8 = Default::default();
let (x, y): (Option<String>, f64) = Default::default();
let (a, b, (c, d)): (i32, u32, (bool, bool)) = Default::default();Making your own:
enum Kind {
A,
B,
C,
}
impl Default for Kind {
fn default() -> Self { Kind::A }
}Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".
Implementors§
impl Default for &CStr
impl Default for &mut str
impl Default for &str
impl Default for ()
impl Default for AHasher
Provides a default Hasher with fixed keys. This is typically used in conjunction with BuildHasherDefault to create AHashers in order to hash the keys of the map.
Generally it is preferable to use RandomState instead, so that different hashmaps will have different keys. However if fixed keys are desirable this may be used instead.
§Example
use std::hash::BuildHasherDefault;
use ahash::{AHasher, RandomState};
use std::collections::HashMap;
let mut map: HashMap<i32, i32, BuildHasherDefault<AHasher>> = HashMap::default();
map.insert(12, 34);impl Default for Abi
impl Default for ActorId
impl Default for Alignment
Returns Alignment::MIN, which is valid for any type.
impl Default for Arc<CStr>
no_global_oom_handling only.impl Default for Arc<str>
no_global_oom_handling only.impl Default for AsciiChar
impl Default for Atomic<bool>
target_has_atomic_load_store=8 only.impl Default for Atomic<i8>
impl Default for Atomic<i16>
impl Default for Atomic<i32>
impl Default for Atomic<i64>
impl Default for Atomic<isize>
impl Default for Atomic<u8>
impl Default for Atomic<u16>
impl Default for Atomic<u32>
impl Default for Atomic<u64>
impl Default for Atomic<usize>
impl Default for AtomicWaker
impl Default for B0
impl Default for B1
impl Default for BigEndian
impl Default for Bits
impl Default for BlockNumberWithHash
impl Default for gstd::prelude::Box<CStr>
impl Default for gstd::prelude::Box<str>
no_global_oom_handling only.impl Default for ByteString
impl Default for CString
impl Default for CodeId
impl Default for scale_decode::error::context::Context
impl Default for scale_encode::error::context::Context
impl Default for Duration
impl Default for Eager
impl Default for core::io::util::Empty
impl Default for Equal
impl Default for Error
impl Default for ErrorBytes
impl Default for ErrorWithGas
impl Default for ErrorWithHandle
impl Default for ErrorWithHash
impl Default for ErrorWithReplyCode
impl Default for ErrorWithSignalCode
impl Default for ErrorWithTwoHashes
impl Default for FormattingOptions
impl Default for alloc::alloc::Global
impl Default for allocator_api2::stable::alloc::global::Global
impl Default for Greater
impl Default for primitive_types::H128
impl Default for primitive_types::H128
impl Default for primitive_types::H160
impl Default for primitive_types::H160
impl Default for primitive_types::H256
impl Default for primitive_types::H256
impl Default for primitive_types::H384
impl Default for primitive_types::H384
impl Default for primitive_types::H512
impl Default for primitive_types::H512
impl Default for primitive_types::H768
impl Default for primitive_types::H768
impl Default for HashWithValue
impl Default for InvalidBufferSize
impl Default for InvalidOutputSize
impl Default for block_buffer::Lazy
impl Default for Less
impl Default for LittleEndian
impl Default for MacError
impl Default for MessageId
impl Default for OnceBool
impl Default for OnceNonZeroUsize
impl Default for PhantomPinned
impl Default for PollNext
impl Default for PortableRegistryBuilder
impl Default for RangeFull
impl Default for Rc<CStr>
no_global_oom_handling only.impl Default for Rc<str>
no_global_oom_handling only.impl Default for Registry
impl Default for ReservationId
impl Default for Reservations
ethexe only.impl Default for Sink
impl Default for SipHasher
impl Default for String
impl Default for TwoHashes
impl Default for TwoHashesWithValue
impl Default for primitive_types::U128
impl Default for primitive_types::U128
impl Default for primitive_types::U256
impl Default for primitive_types::U256
impl Default for primitive_types::U512
impl Default for primitive_types::U512
impl Default for UTerm
impl Default for Z0
impl Default for bool
impl Default for char
impl Default for f16
impl Default for f32
impl Default for f64
impl Default for f128
impl Default for i8
impl Default for i16
impl Default for i32
impl Default for i64
impl Default for i128
impl Default for isize
impl Default for u8
impl Default for u16
impl Default for u32
impl Default for u64
impl Default for u128
impl Default for usize
impl<'a, K, V> Default for gstd::prelude::collections::btree_map::Iter<'a, K, V>where
K: 'a,
V: 'a,
impl<'a, K, V> Default for gstd::prelude::collections::btree_map::IterMut<'a, K, V>where
K: 'a,
V: 'a,
impl<'a, T> Default for OnceRef<'a, T>
impl<'a> Default for &'a ByteStr
impl<'a> Default for &'a mut ByteStr
impl<'a> Default for PhantomContravariantLifetime<'a>
impl<'a> Default for PhantomCovariantLifetime<'a>
impl<'a> Default for PhantomInvariantLifetime<'a>
impl<A, B> Default for Chain<A, B>
impl<A> Default for allocator_api2::stable::boxed::Box<str, A>
impl<A> Default for RepeatN<A>
Creates an empty iterator, like repeat_n(value, 0)
but without needing any such value at hand.
impl<A> Default for SmallVec<A>where
A: Array,
impl<B> Default for Cow<'_, B>
impl<BlockSize, Kind> Default for BlockBuffer<BlockSize, Kind>
impl<F, N, T> Default for FieldBuilder<F, N, T>where
F: Form,
impl<F, S> Default for TypeBuilder<F, S>where
F: Form,
impl<F, T> Default for FieldsBuilder<F, T>where
F: Form,
impl<F> Default for OptionFuture<F>
impl<F> Default for Variants<F>
impl<Fut> Default for FuturesOrdered<Fut>where
Fut: Future,
impl<Fut> Default for FuturesUnordered<Fut>
impl<H> Default for BuildHasherDefault<H>
impl<I> Default for Cloned<I>where
I: Default,
impl<I> Default for Copied<I>where
I: Default,
impl<I> Default for Enumerate<I>where
I: Default,
impl<I> Default for Flatten<I>
impl<I> Default for Fuse<I>where
I: Default,
impl<I> Default for Rev<I>where
I: Default,
impl<Idx> Default for gstd::prelude::ops::Range<Idx>where
Idx: Default,
impl<Idx> Default for core::range::Range<Idx>where
Idx: Default,
impl<K, V, A> Default for gstd::prelude::collections::btree_map::IntoIter<K, V, A>where
A: AllocatorClone + Default,
impl<K, V, A> Default for IntoKeys<K, V, A>where
A: AllocatorClone + Default,
impl<K, V, A> Default for IntoValues<K, V, A>where
A: AllocatorClone + Default,
impl<K, V, S, A> Default for HashMap<K, V, S, A>
impl<K, V> Default for BTreeMap<K, V>
impl<K, V> Default for Keys<'_, K, V>
impl<K, V> Default for gstd::prelude::collections::btree_map::Range<'_, K, V>
impl<K, V> Default for RangeMut<'_, K, V>
impl<K, V> Default for Values<'_, K, V>
impl<K, V> Default for ValuesMut<'_, K, V>
impl<O> Default for F32<O>
impl<O> Default for F64<O>
impl<O> Default for I16<O>
impl<O> Default for I32<O>
impl<O> Default for I64<O>
impl<O> Default for I128<O>
impl<O> Default for Isize<O>
impl<O> Default for U16<O>
impl<O> Default for U32<O>
impl<O> Default for U64<O>
impl<O> Default for zerocopy::byteorder::U128<O>
impl<O> Default for Usize<O>
impl<P> Default for MaybeDangling<P>
impl<R> Default for IgnoreVisitor<R>
impl<St> Default for SelectAll<St>
impl<T, A> Default for allocator_api2::stable::boxed::Box<[T], A>
impl<T, A> Default for HashTable<T, A>
impl<T, A> Default for gstd::prelude::vec::IntoIter<T, A>
impl<T, A> Default for gstd::prelude::collections::btree_set::IntoIter<T, A>where
A: AllocatorClone + Default,
impl<T, N> Default for GenericArray<T, N>where
T: Default,
N: ArrayLength<T>,
impl<T, OutSize, O> Default for CtVariableCoreWrapper<T, OutSize, O>where
T: VariableOutputCore,
OutSize: ArrayLength<u8> + IsLessOrEqual<<T as OutputSizeUser>::OutputSize>,
<OutSize as IsLessOrEqual<<T as OutputSizeUser>::OutputSize>>::Output: NonZero,
<T as BlockSizeUser>::BlockSize: IsLess<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UTerm, B1>, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>,
<<T as BlockSizeUser>::BlockSize as IsLess<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UTerm, B1>, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>>::Output: NonZero,
impl<T, S, A> Default for HashSet<T, S, A>
impl<T, const CAP: usize> Default for ArrayVec<T, CAP>
impl<T, const N: usize> Default for gstd::prelude::array::IntoIter<T, N>
impl<T, const N: usize> Default for Mask<T, N>where
T: MaskElement,
impl<T, const N: usize> Default for Simd<T, N>where
T: SimdElement + Default,
impl<T, const VARIANT: u32, const FIELD: u32> Default for FieldRepresentingType<T, VARIANT, FIELD>where
T: ?Sized,
impl<T: Default> Default for Mutex<T>
impl<T: Default> Default for RwLock<T>
impl<T> Default for &[T]
impl<T> Default for &mut [T]
impl<T> Default for (T₁, T₂, …, Tₙ)where
T: Default,
This trait is implemented for tuples up to twelve items long.
impl<T> Default for *const T
impl<T> Default for *mut T
impl<T> Default for Arc<T>where
T: Default,
no_global_oom_handling only.impl<T> Default for Arc<[T]>
no_global_oom_handling only.impl<T> Default for AssertUnwindSafe<T>where
T: Default,
impl<T> Default for Atomic<*mut T>
target_has_atomic_load_store=ptr only.impl<T> Default for BTreeSet<T>
impl<T> Default for BinaryHeap<T>
impl<T> Default for gstd::prelude::Box<T>where
T: Default,
no_global_oom_handling only.impl<T> Default for allocator_api2::stable::boxed::Box<T>where
T: Default,
no_global_oom_handling only.impl<T> Default for gstd::prelude::Box<[T]>
no_global_oom_handling only.impl<T> Default for Cell<T>where
T: Default,
impl<T> Default for Complex<T>where
T: Default,
impl<T> Default for CoreWrapper<T>where
T: Default + BufferKindUser,
<T as BlockSizeUser>::BlockSize: IsLess<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UTerm, B1>, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>> + Default,
<<T as BlockSizeUser>::BlockSize as IsLess<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UInt<UTerm, B1>, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>>::Output: NonZero,
<T as BufferKindUser>::BufferKind: Default,
impl<T> Default for Cursor<T>where
T: Default,
impl<T> Default for gstd::prelude::iter::Empty<T>
impl<T> Default for Interner<T>where
T: Ord,
impl<T> Default for gstd::prelude::collections::binary_heap::IntoIter<T>
impl<T> Default for gstd::prelude::collections::linked_list::IntoIter<T>
impl<T> Default for gstd::prelude::slice::Iter<'_, T>
impl<T> Default for gstd::prelude::collections::binary_heap::Iter<'_, T>
impl<T> Default for gstd::prelude::collections::btree_set::Iter<'_, T>
impl<T> Default for gstd::prelude::collections::linked_list::Iter<'_, T>
impl<T> Default for gstd::prelude::collections::vec_deque::Iter<'_, T>
impl<T> Default for gstd::prelude::slice::IterMut<'_, T>
impl<T> Default for gstd::prelude::collections::linked_list::IterMut<'_, T>
impl<T> Default for gstd::prelude::collections::vec_deque::IterMut<'_, T>
impl<T> Default for once_cell::unsync::Lazy<T>where
T: Default,
impl<T> Default for LazyCell<T>where
T: Default,
impl<T> Default for LinkedList<T>
impl<T> Default for ManuallyDrop<T>
impl<T> Default for OnceBox<T>
impl<T> Default for gstd::prelude::cell::OnceCell<T>
impl<T> Default for once_cell::unsync::OnceCell<T>
impl<T> Default for Option<T>
impl<T> Default for Path<T>where
T: Form,
impl<T> Default for PhantomContravariant<T>where
T: ?Sized,
impl<T> Default for PhantomCovariant<T>where
T: ?Sized,
impl<T> Default for PhantomData<T>where
T: ?Sized,
impl<T> Default for PhantomInvariant<T>where
T: ?Sized,
impl<T> Default for Pin<Arc<T>>
no_global_oom_handling only.impl<T> Default for Pin<Box<T>>
no_global_oom_handling only.impl<T> Default for Pin<Rc<T>>
no_global_oom_handling only.impl<T> Default for gstd::prelude::collections::btree_set::Range<'_, T>
impl<T> Default for Rc<T>where
T: Default,
no_global_oom_handling only.impl<T> Default for Rc<[T]>
no_global_oom_handling only.