Skip to content

Commit 89187f3

Browse files
authored
Unrolled build for #146924
Rollup merge of #146924 - cptpiepmatz:doc-nonzero-const-creation, r=joboet Add doc for `NonZero*` const creation I ran into trouble using `NonZero*` values because I didn’t see any clear way to create them at compile time. At first I ended up using `NonZero*::new_unchecked` a lot, until I realized that `Option::unwrap` and `Option::expect` are `const` and can be used in a `const` context. With that, you can create non-zero values at compile time safely, without touching `unsafe`. This wasn’t obvious to me and my peers who’ve been using Rust for a while, so I thought adding a note to the docs would make it easier for others to discover. If this should be worded differently or placed in another location, we can do that. I just want to make this more obvious.
2 parents eabf390 + 185ae69 commit 89187f3

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

library/core/src/num/nonzero.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -548,6 +548,18 @@ macro_rules! nonzero_integer {
548548
#[doc = concat!("assert_eq!(align_of::<", stringify!($Ty), ">(), align_of::<Option<", stringify!($Ty), ">>());")]
549549
/// ```
550550
///
551+
/// # Compile-time creation
552+
///
553+
/// Since both [`Option::unwrap()`] and [`Option::expect()`] are `const`, it is possible to
554+
/// define a new
555+
#[doc = concat!("`", stringify!($Ty), "`")]
556+
/// at compile time via:
557+
/// ```
558+
#[doc = concat!("use std::num::", stringify!($Ty), ";")]
559+
///
560+
#[doc = concat!("const TEN: ", stringify!($Ty), " = ", stringify!($Ty) , r#"::new(10).expect("ten is non-zero");"#)]
561+
/// ```
562+
///
551563
/// [null pointer optimization]: crate::option#representation
552564
#[$stability]
553565
pub type $Ty = NonZero<$Int>;

0 commit comments

Comments
 (0)