Skip to content

Commit 085fbe9

Browse files
authoredApr 28, 2023
Rollup merge of #110620 - Nilstrieb:document-the-undocumented, r=thomcc
Document `const {}` syntax for `std::thread_local`. It exists and is pretty cool. More people should use it. It was added in #83416 and stabilized in #91355 with the tracking issue #84223.
2 parents 6b0da57 + b56d85d commit 085fbe9

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed
 

‎library/std/src/thread/local.rs

+20-2
Original file line numberDiff line numberDiff line change
@@ -134,10 +134,28 @@ impl<T: 'static> fmt::Debug for LocalKey<T> {
134134
/// thread_local! {
135135
/// pub static FOO: RefCell<u32> = RefCell::new(1);
136136
///
137-
/// #[allow(unused)]
138137
/// static BAR: RefCell<f32> = RefCell::new(1.0);
139138
/// }
140-
/// # fn main() {}
139+
///
140+
/// FOO.with(|foo| assert_eq!(*foo.borrow(), 1));
141+
/// BAR.with(|bar| assert_eq!(*bar.borrow(), 1.0));
142+
/// ```
143+
///
144+
/// This macro supports a special `const {}` syntax that can be used
145+
/// when the initialization expression can be evaluated as a constant.
146+
/// This can enable a more efficient thread local implementation that
147+
/// can avoid lazy initialization. For types that do not
148+
/// [need to be dropped][crate::mem::needs_drop], this can enable an
149+
/// even more efficient implementation that does not need to
150+
/// track any additional state.
151+
///
152+
/// ```
153+
/// use std::cell::Cell;
154+
/// thread_local! {
155+
/// pub static FOO: Cell<u32> = const { Cell::new(1) };
156+
/// }
157+
///
158+
/// FOO.with(|foo| assert_eq!(foo.get(), 1));
141159
/// ```
142160
///
143161
/// See [`LocalKey` documentation][`std::thread::LocalKey`] for more

0 commit comments

Comments
 (0)
Please sign in to comment.