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 · 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", so this trait is not object safe.
Implementors§
impl Default for &str
impl Default for &CStr
impl Default for &OsStr
impl Default for &Bytes
impl Default for &mut str
impl Default for AsciiChar
impl Default for Abi
impl Default for Endian
impl Default for BigEndian
impl Default for LittleEndian
impl Default for Network
impl Default for CanisterInstallMode
impl Default for EcdsaCurve
impl Default for HttpMethod
impl Default for LogVisibility
impl Default for SchnorrAlgorithm
impl Default for WasmMemoryPersistence
impl Default for MonthRepr
Creates a modifier that indicates the value uses the
Numerical representation.
impl Default for Padding
Creates a modifier that indicates the value is padded with zeroes.
impl Default for SubsecondDigits
Creates a modifier that indicates the stringified value contains one or more digits.
impl Default for UnixTimestampPrecision
Creates a modifier that indicates the value represents the number of seconds since the Unix epoch.
impl Default for WeekNumberRepr
Creates a modifier that indicates that the value uses the Iso representation.
impl Default for WeekdayRepr
Creates a modifier that indicates the value uses the Long representation.
impl Default for YearRange
Creates a modifier that indicates the value uses the Extended range.
impl Default for YearRepr
Creates a modifier that indicates the value uses the Full representation.
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 ()
impl Default for usize
impl Default for IndexStoreRegistry
impl Default for DeleteSpec
impl Default for LoadSpec
impl Default for CoercionSpec
impl Default for EntityCounters
impl Default for EntitySummary
impl Default for EventOps
impl Default for EventPerf
impl Default for EventReport
impl Default for EventSelect
impl Default for EventState
impl Default for DataStoreSnapshot
impl Default for EntitySnapshot
impl Default for IndexStoreSnapshot
impl Default for StorageReport
impl Default for Generator
impl Default for Account
impl Default for icydb_core::types::Blob
impl Default for Date
impl Default for icydb_core::types::Decimal
impl Default for icydb_core::types::Duration
impl Default for E8s
impl Default for E18s
impl Default for Float32
impl Default for Float64
impl Default for Int128
impl Default for icydb_core::types::Int
impl Default for Nat128
impl Default for icydb_core::types::Nat
impl Default for Principal
impl Default for Subaccount
impl Default for Timestamp
impl Default for icydb_core::types::Ulid
impl Default for Unit
impl Default for Issue
impl Default for SanitizeVisitor
impl Default for VisitorIssues
impl Default for ValidateVisitor
impl Default for Global
impl Default for Box<str>
no_global_oom_handling only.impl Default for Box<CStr>
impl Default for Box<OsStr>
impl Default for Box<Bytes>
std or alloc only.impl Default for ByteString
impl Default for CString
impl Default for Rc<str>
no_global_oom_handling only.impl Default for Rc<CStr>
no_global_oom_handling only.impl Default for String
impl Default for Arc<str>
no_global_oom_handling only.impl Default for Arc<CStr>
no_global_oom_handling only.impl Default for Error
impl Default for FormattingOptions
impl Default for SipHasher
impl Default for PhantomPinned
impl Default for RangeFull
impl Default for Alignment
Returns Alignment::MIN, which is valid for any type.
impl Default for AtomicBool
target_has_atomic_load_store=8 only.impl Default for AtomicI8
impl Default for AtomicI16
impl Default for AtomicI32
impl Default for AtomicI64
impl Default for AtomicIsize
impl Default for AtomicU8
impl Default for AtomicU16
impl Default for AtomicU32
impl Default for AtomicU64
impl Default for AtomicUsize
impl Default for core::time::Duration
impl Default for System
impl Default for OsString
impl Default for FileTimes
impl Default for DefaultHasher
impl Default for RandomState
impl Default for std::io::util::Empty
impl Default for Sink
impl Default for PathBuf
impl Default for ExitCode
The default value is ExitCode::SUCCESS
impl Default for ExitStatus
The default value is one which indicates successful completion.
impl Default for DefaultRandomSource
impl Default for std::sync::nonpoison::condvar::Condvar
impl Default for std::sync::poison::condvar::Condvar
impl Default for anyhow::Chain<'_>
std or non-anyhow_no_core_error only.impl Default for ReadOptions
impl Default for NullString
impl Default for NullWideString
impl Default for Eager
impl Default for Lazy
impl Default for DecoderConfig
impl Default for DocComments
impl Default for IDLBuilder
impl Default for TypeSerialize
impl Default for ValueSerializer
impl Default for TypeContainer
impl Default for candid::types::number::Int
impl Default for candid::types::number::Nat
impl Default for Reserved
impl Default for TypeEnv
impl Default for canic_cdk::spec::standards::icrc::icrc21::FieldsDisplay
impl Default for Cycles
impl Default for DateTime<FixedOffset>
impl Default for DateTime<Utc>
impl Default for Parsed
impl Default for NaiveDate
The default value for a NaiveDate is 1st of January 1970.
§Example
use chrono::NaiveDate;
let default_date = NaiveDate::default();
assert_eq!(default_date, NaiveDate::from_ymd_opt(1970, 1, 1).unwrap());impl Default for NaiveDateTime
The default value for a NaiveDateTime is 1st of January 1970 at 00:00:00.
Note that while this may look like the UNIX epoch, it is missing the
time zone. The actual UNIX epoch cannot be expressed by this type,
however it is available as DateTime::UNIX_EPOCH.
impl Default for NaiveTime
The default value for a NaiveTime is midnight, 00:00:00 exactly.
§Example
use chrono::NaiveTime;
let default_time = NaiveTime::default();
assert_eq!(default_time, NaiveTime::from_hms_opt(0, 0, 0).unwrap());impl Default for TimeDelta
impl Default for WeekdaySet
impl Default for Converter
impl Default for Hasher
impl Default for Specification
alloc only.impl Default for InvalidBufferSize
impl Default for InvalidOutputSize
impl Default for bf16
impl Default for f16
impl Default for SignatureMap
impl Default for TaskId
impl Default for GetBalanceRequest
impl Default for GetBlockHeadersRequest
impl Default for GetBlockHeadersResponse
impl Default for GetCurrentFeePercentilesRequest
impl Default for GetUtxosRequest
impl Default for GetUtxosResponse
impl Default for Outpoint
impl Default for SendTransactionRequest
impl Default for Utxo
impl Default for ic_cdk::management_canister::CreateCanisterArgs
impl Default for ic_cdk::management_canister::ProvisionalCreateCanisterWithCyclesArgs
impl Default for CanisterStableMemory
impl Default for StableIO
impl Default for StableReader
impl Default for StableWriter
impl Default for Bip341
impl Default for CanisterSettings
impl Default for ic_management_canister_types::CreateCanisterArgs
impl Default for DefiniteCanisterSettings
impl Default for EcdsaKeyId
impl Default for EcdsaPublicKeyArgs
impl Default for EcdsaPublicKeyResult
impl Default for EnvironmentVariable
impl Default for HttpHeader
impl Default for HttpRequestArgs
impl Default for HttpRequestResult
impl Default for ic_management_canister_types::ProvisionalCreateCanisterWithCyclesArgs
impl Default for SchnorrKeyId
impl Default for SchnorrPublicKeyArgs
impl Default for SchnorrPublicKeyResult
impl Default for SignWithEcdsaArgs
impl Default for SignWithEcdsaResult
impl Default for SignWithSchnorrArgs
impl Default for SignWithSchnorrResult
impl Default for Snapshot
impl Default for UpgradeFlags
impl Default for VetKDDeriveKeyResult
impl Default for VetKDPublicKeyResult
impl Default for G1Affine
impl Default for G1Projective
impl Default for G2Affine
impl Default for G2Projective
impl Default for Gt
impl Default for MillerLoopResult
impl Default for Scalar
impl Default for Memo
impl Default for icrc_ledger_types::icrc21::responses::FieldsDisplay
impl Default for Buffer
impl Default for BigInt
impl Default for BigUint
impl Default for FormatterOptions
impl Default for rust_decimal::decimal::Decimal
impl Default for ByteBuf
impl Default for IgnoredAny
impl Default for DefaultKey
impl Default for KeyData
impl Default for time::duration::Duration
impl Default for Day
Creates a modifier that indicates the value is padded with zeroes.
impl Default for End
Creates a modifier used to represent the end of input.
impl Default for Hour
Creates a modifier that indicates the value is padded with zeroes and has the 24-hour representation.
impl Default for Minute
Creates a modifier that indicates the value is padded with zeroes.
impl Default for Month
Creates an instance of this type that indicates the value uses the
Numerical representation, is padded with zeroes,
and is case-sensitive when parsing.
impl Default for OffsetHour
Creates a modifier that indicates the value only uses a sign for negative values and is padded with zeroes.
impl Default for OffsetMinute
Creates a modifier that indicates the value is padded with zeroes.
impl Default for OffsetSecond
Creates a modifier that indicates the value is padded with zeroes.
impl Default for Ordinal
Creates a modifier that indicates the value is padded with zeroes.
impl Default for Period
Creates a modifier that indicates the value uses the upper-case representation and is case-sensitive when parsing.
impl Default for Second
Creates a modifier that indicates the value is padded with zeroes.
impl Default for Subsecond
Creates a modifier that indicates the stringified value contains one or more digits.
impl Default for UnixTimestamp
Creates a modifier that indicates the value represents the number of seconds since the Unix epoch. The sign is not mandatory.
impl Default for WeekNumber
Creates a modifier that indicates that the value is padded with zeroes
and uses the Iso representation.
impl Default for Weekday
Creates a modifier that indicates the value uses the Long
representation and is case-sensitive when parsing. If the representation is changed to a
numerical one, the instance defaults to one-based indexing.
impl Default for Year
Creates a modifier that indicates the value uses the Full
representation, is padded with zeroes, uses the Gregorian calendar as its
base, and only includes the year’s sign if necessary.
impl Default for B0
impl Default for B1
impl Default for Z0
impl Default for Equal
impl Default for Greater
impl Default for Less
impl Default for UTerm
impl Default for ulid::Ulid
impl Default for Xxh3
impl Default for Xxh3Builder
impl Default for Xxh3Default
impl Default for Xxh3DefaultBuilder
impl Default for vec128_storage
impl Default for vec256_storage
impl Default for vec512_storage
impl<'a> Default for &'a ByteStr
impl<'a> Default for &'a mut ByteStr
impl<'a> Default for HashTree<'a>
impl<'a> Default for PhantomContravariantLifetime<'a>
impl<'a> Default for PhantomCovariantLifetime<'a>
impl<'a> Default for PhantomInvariantLifetime<'a>
impl<'a, D, A> Default for BuildDoc<'a, D, A>where
D: DocPtr<'a, A>,
impl<'a, K, V> Default for alloc::collections::btree::map::Iter<'a, K, V>where
K: 'a,
V: 'a,
impl<'a, K, V> Default for alloc::collections::btree::map::IterMut<'a, K, V>where
K: 'a,
V: 'a,
impl<'a, T, A> Default for Doc<'a, T, A>where
T: DocPtr<'a, A>,
impl<A> Default for arrayvec::array_string::ArrayString<A>
impl<A> Default for arrayvec::ArrayVec<A>where
A: Array,
impl<A> Default for pretty::Arena<'_, A>
impl<A> Default for SmallVec<A>where
A: Array,
impl<A, B> Default for core::iter::adapters::chain::Chain<A, B>
impl<B> Default for Cow<'_, B>
impl<BlockSize, Kind> Default for BlockBuffer<BlockSize, Kind>
impl<E> Default for Ref<E>
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 core::ops::range::Range<Idx>where
Idx: Default,
impl<Idx> Default for core::range::Range<Idx>where
Idx: Default,
impl<K> Default for std::collections::hash::set::IntoIter<K>
impl<K> Default for std::collections::hash::set::Iter<'_, K>
impl<K, V> Default for ic_certification::nested_rb_tree::NestedTree<K, V>where
K: NestedTreeKeyRequirements,
V: NestedTreeValueRequirements,
impl<K, V> Default for ic_certification::nested_rb_tree::NestedTree<K, V>where
K: NestedTreeKeyRequirements,
V: NestedTreeValueRequirements,
impl<K, V> Default for BTreeMap<K, V>
impl<K, V> Default for alloc::collections::btree::map::Keys<'_, K, V>
impl<K, V> Default for alloc::collections::btree::map::Range<'_, K, V>
impl<K, V> Default for RangeMut<'_, K, V>
impl<K, V> Default for alloc::collections::btree::map::Values<'_, K, V>
impl<K, V> Default for alloc::collections::btree::map::ValuesMut<'_, K, V>
impl<K, V> Default for std::collections::hash::map::IntoIter<K, V>
impl<K, V> Default for std::collections::hash::map::IntoKeys<K, V>
impl<K, V> Default for std::collections::hash::map::IntoValues<K, V>
impl<K, V> Default for std::collections::hash::map::Iter<'_, K, V>
impl<K, V> Default for std::collections::hash::map::IterMut<'_, K, V>
impl<K, V> Default for std::collections::hash::map::Keys<'_, K, V>
impl<K, V> Default for std::collections::hash::map::Values<'_, K, V>
impl<K, V> Default for std::collections::hash::map::ValuesMut<'_, K, V>
impl<K, V> Default for ic_certification::rb_tree::RbTree<K, V>
impl<K, V> Default for ic_certification::rb_tree::RbTree<K, V>
impl<K, V> Default for ic_certified_map::rbtree::RbTree<K, V>
impl<K, V> Default for SlotMap<K, V>where
K: Key,
impl<K, V> Default for DenseSlotMap<K, V>where
K: Key,
impl<K, V> Default for HopSlotMap<K, V>where
K: Key,
impl<K, V> Default for SecondaryMap<K, V>where
K: Key,
impl<K, V, A> Default for alloc::collections::btree::map::IntoIter<K, V, A>
impl<K, V, A> Default for alloc::collections::btree::map::IntoKeys<K, V, A>
impl<K, V, A> Default for alloc::collections::btree::map::IntoValues<K, V, A>
impl<K, V, S> Default for HashMap<K, V, S>where
S: Default,
impl<K, V, S> Default for SparseSecondaryMap<K, V, S>
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 U128<O>
impl<O> Default for Usize<O>
impl<P> Default for MaybeDangling<P>
impl<R> Default for UnwrapErr<R>
impl<T> Default for &[T]
impl<T> Default for &mut [T]
impl<T> Default for Option<T>
impl<T> Default for [T; 0]
impl<T> Default for [T; 1]where
T: Default,
impl<T> Default for [T; 2]where
T: Default,
impl<T> Default for [T; 3]where
T: Default,
impl<T> Default for [T; 4]where
T: Default,
impl<T> Default for [T; 5]where
T: Default,
impl<T> Default for [T; 6]where
T: Default,
impl<T> Default for [T; 7]where
T: Default,
impl<T> Default for [T; 8]where
T: Default,
impl<T> Default for [T; 9]where
T: Default,
impl<T> Default for [T; 10]where
T: Default,
impl<T> Default for [T; 11]where
T: Default,
impl<T> Default for [T; 12]where
T: Default,
impl<T> Default for [T; 13]where
T: Default,
impl<T> Default for [T; 14]where
T: Default,
impl<T> Default for [T; 15]where
T: Default,
impl<T> Default for [T; 16]where
T: Default,
impl<T> Default for [T; 17]where
T: Default,
impl<T> Default for [T; 18]where
T: Default,
impl<T> Default for [T; 19]where
T: Default,
impl<T> Default for [T; 20]where
T: Default,
impl<T> Default for [T; 21]where
T: Default,
impl<T> Default for [T; 22]where
T: Default,
impl<T> Default for [T; 23]where
T: Default,
impl<T> Default for [T; 24]where
T: Default,
impl<T> Default for [T; 25]where
T: Default,
impl<T> Default for [T; 26]where
T: Default,
impl<T> Default for [T; 27]where
T: Default,
impl<T> Default for [T; 28]where
T: Default,
impl<T> Default for [T; 29]where
T: Default,
impl<T> Default for [T; 30]where
T: Default,
impl<T> Default for [T; 31]where
T: Default,
impl<T> Default for [T; 32]where
T: Default,
impl<T> Default for *const 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 Box<[T]>
no_global_oom_handling only.impl<T> Default for Box<T>where
T: Default,
no_global_oom_handling only.impl<T> Default for BinaryHeap<T>
impl<T> Default for alloc::collections::binary_heap::IntoIter<T>
impl<T> Default for alloc::collections::binary_heap::Iter<'_, T>
impl<T> Default for BTreeSet<T>
impl<T> Default for alloc::collections::btree::set::Iter<'_, T>
impl<T> Default for alloc::collections::btree::set::Range<'_, T>
impl<T> Default for alloc::collections::linked_list::IntoIter<T>
impl<T> Default for alloc::collections::linked_list::Iter<'_, T>
impl<T> Default for alloc::collections::linked_list::IterMut<'_, T>
impl<T> Default for LinkedList<T>
impl<T> Default for alloc::collections::vec_deque::iter::Iter<'_, T>
impl<T> Default for alloc::collections::vec_deque::iter_mut::IterMut<'_, T>
impl<T> Default for VecDeque<T>
impl<T> Default for Rc<[T]>
no_global_oom_handling only.impl<T> Default for Rc<T>where
T: Default,
no_global_oom_handling only.impl<T> Default for alloc::rc::Weak<T>
impl<T> Default for Arc<[T]>
no_global_oom_handling only.impl<T> Default for Arc<T>where
T: Default,
no_global_oom_handling only.impl<T> Default for alloc::sync::Weak<T>
impl<T> Default for Vec<T>
impl<T> Default for LazyCell<T>where
T: Default,
impl<T> Default for OnceCell<T>
impl<T> Default for Cell<T>where
T: Default,
impl<T> Default for RefCell<T>where
T: Default,
impl<T> Default for SyncUnsafeCell<T>where
T: Default,
impl<T> Default for UnsafeCell<T>where
T: Default,
impl<T> Default for Reverse<T>where
T: Default,
impl<T> Default for core::iter::sources::empty::Empty<T>
impl<T> Default for PhantomData<T>where
T: ?Sized,
impl<T> Default for PhantomContravariant<T>where
T: ?Sized,
impl<T> Default for PhantomCovariant<T>where
T: ?Sized,
impl<T> Default for PhantomInvariant<T>where
T: ?Sized,
impl<T> Default for ManuallyDrop<T>
impl<T> Default for Saturating<T>where
T: Default,
impl<T> Default for Wrapping<T>where
T: Default,
impl<T> Default for AssertUnwindSafe<T>where
T: Default,
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 Pin<Arc<T>>
no_global_oom_handling only.impl<T> Default for UnsafePinned<T>where
T: Default,
impl<T> Default for core::slice::iter::Iter<'_, T>
impl<T> Default for core::slice::iter::IterMut<'_, T>
impl<T> Default for AtomicPtr<T>
target_has_atomic_load_store=ptr only.