Skip to content

Commit 160ddb1

Browse files
jethrogbJohnTitor
authored andcommitted
Clarify defining static items in a generic scope
1 parent 91fb8ee commit 160ddb1

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/items/static-items.md

+48
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,54 @@ statics:
2626
The initializer expression must be omitted in an [external block], and must be
2727
provided for free static items.
2828

29+
## Statics & generics
30+
31+
A static item defined in a generic scope (for example in a blanket or default
32+
implementation) will result in exactly one static item being defined, as if
33+
the static definition was pulled out of the current scope into the module.
34+
There will *not* be one item per monomorphization.
35+
36+
This code:
37+
38+
```rust
39+
use std::sync::atomic::{AtomicUsize, Ordering};
40+
41+
trait Tr {
42+
fn default_impl() {
43+
static COUNTER: AtomicUsize = AtomicUsize::new(0);
44+
println!("counter was {}", COUNTER.fetch_add(1, Ordering::Relaxed));
45+
}
46+
47+
fn blanket_impl();
48+
}
49+
50+
struct Ty1 {}
51+
struct Ty2 {}
52+
53+
impl<T> Tr for T {
54+
fn blanket_impl() {
55+
static COUNTER: AtomicUsize = AtomicUsize::new(0);
56+
println!("counter was {}", COUNTER.fetch_add(1, Ordering::Relaxed));
57+
}
58+
}
59+
60+
fn main() {
61+
<Ty1 as Tr>::default_impl();
62+
<Ty2 as Tr>::default_impl();
63+
<Ty1 as Tr>::blanket_impl();
64+
<Ty2 as Tr>::blanket_impl();
65+
}
66+
```
67+
68+
prints
69+
70+
```text
71+
counter was 0
72+
counter was 1
73+
counter was 0
74+
counter was 1
75+
```
76+
2977
## Mutable statics
3078

3179
If a static item is declared with the `mut` keyword, then it is allowed to be

0 commit comments

Comments
 (0)