From b56d85dc09b774b432c24979d364b7aeb4b75e2f Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Thu, 20 Apr 2023 19:48:08 +0200 Subject: [PATCH] Document `const {}` syntax for `std::thread_local`. It exists and is pretty cool. More people should use it. --- library/std/src/thread/local.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/library/std/src/thread/local.rs b/library/std/src/thread/local.rs index fa08fdc16530b..3b7c31826b962 100644 --- a/library/std/src/thread/local.rs +++ b/library/std/src/thread/local.rs @@ -134,10 +134,28 @@ impl fmt::Debug for LocalKey { /// thread_local! { /// pub static FOO: RefCell = RefCell::new(1); /// -/// #[allow(unused)] /// static BAR: RefCell = RefCell::new(1.0); /// } -/// # fn main() {} +/// +/// FOO.with(|foo| assert_eq!(*foo.borrow(), 1)); +/// BAR.with(|bar| assert_eq!(*bar.borrow(), 1.0)); +/// ``` +/// +/// This macro supports a special `const {}` syntax that can be used +/// when the initialization expression can be evaluated as a constant. +/// This can enable a more efficient thread local implementation that +/// can avoid lazy initialization. For types that do not +/// [need to be dropped][crate::mem::needs_drop], this can enable an +/// even more efficient implementation that does not need to +/// track any additional state. +/// +/// ``` +/// use std::cell::Cell; +/// thread_local! { +/// pub static FOO: Cell = const { Cell::new(1) }; +/// } +/// +/// FOO.with(|foo| assert_eq!(foo.get(), 1)); /// ``` /// /// See [`LocalKey` documentation][`std::thread::LocalKey`] for more