about summary refs log tree commit diff
path: root/library/core/src
diff options
context:
space:
mode:
authorMatthias Krüger <476013+matthiaskrgr@users.noreply.github.com>2025-09-25 18:15:10 +0200
committerGitHub <noreply@github.com>2025-09-25 18:15:10 +0200
commit781f71a6fee007c0b9dc93e2aaf5426ab8e24049 (patch)
tree5645ca095f5c1571ee4f2e3173cbb8ff0562ef13 /library/core/src
parent83cf8f98600a18c690ce890bd7c0f25c14351815 (diff)
parent185ae698aabe0f6f7cc5ef7eeed13a556bce5334 (diff)
downloadrust-781f71a6fee007c0b9dc93e2aaf5426ab8e24049.tar.gz
rust-781f71a6fee007c0b9dc93e2aaf5426ab8e24049.zip
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.
Diffstat (limited to 'library/core/src')
-rw-r--r--library/core/src/num/nonzero.rs12
1 files changed, 12 insertions, 0 deletions
diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs
index 1b7c28bb95a..d9184e3c9c2 100644
--- a/library/core/src/num/nonzero.rs
+++ b/library/core/src/num/nonzero.rs
@@ -548,6 +548,18 @@ macro_rules! nonzero_integer {
         #[doc = concat!("assert_eq!(align_of::<", stringify!($Ty), ">(), align_of::<Option<", stringify!($Ty), ">>());")]
         /// ```
         ///
+        /// # Compile-time creation
+        ///
+        /// Since both [`Option::unwrap()`] and [`Option::expect()`] are `const`, it is possible to
+        /// define a new
+        #[doc = concat!("`", stringify!($Ty), "`")]
+        /// at compile time via:
+        /// ```
+        #[doc = concat!("use std::num::", stringify!($Ty), ";")]
+        ///
+        #[doc = concat!("const TEN: ", stringify!($Ty), " = ", stringify!($Ty) , r#"::new(10).expect("ten is non-zero");"#)]
+        /// ```
+        ///
         /// [null pointer optimization]: crate::option#representation
         #[$stability]
         pub type $Ty = NonZero<$Int>;