From 3291cb6c62c1d61178885c7af4b8c7f521aab04b Mon Sep 17 00:00:00 2001 From: "Dustin J. Mitchell" <djmitche@google.com> Date: Thu, 16 Jan 2025 04:18:29 -0500 Subject: [PATCH] Make const slide less silly (#2557) A constant named ZERO that does not contain zero seems pretty silly! This also shows an example of a const fn. --- src/user-defined-types/const.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/user-defined-types/const.md b/src/user-defined-types/const.md index 102ca0c5..02ea6b5c 100644 --- a/src/user-defined-types/const.md +++ b/src/user-defined-types/const.md @@ -11,10 +11,18 @@ they are used: ```rust,editable const DIGEST_SIZE: usize = 3; -const ZERO: Option<u8> = Some(42); +const FILL_VALUE: u8 = calculate_fill_value(); + +const fn calculate_fill_value() -> u8 { + if DIGEST_SIZE < 10 { + 42 + } else { + 13 + } +} fn compute_digest(text: &str) -> [u8; DIGEST_SIZE] { - let mut digest = [ZERO.unwrap_or(0); DIGEST_SIZE]; + let mut digest = [FILL_VALUE; DIGEST_SIZE]; for (idx, &b) in text.as_bytes().iter().enumerate() { digest[idx % DIGEST_SIZE] = digest[idx % DIGEST_SIZE].wrapping_add(b); }