Skip to content

Commit f817ed6

Browse files
authored
Clarify defining static items in a generic scope
1 parent 04d5d5d commit f817ed6

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/items/static-items.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,54 @@ statics:
2121
through a reference.
2222
* Constants cannot refer to statics.
2323

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

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

0 commit comments

Comments
 (0)