File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change @@ -21,6 +21,54 @@ statics:
21
21
through a reference.
22
22
* Constants cannot refer to statics.
23
23
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
+
24
72
## Mutable statics
25
73
26
74
If a static item is declared with the ` mut ` keyword, then it is allowed to be
You can’t perform that action at this time.
0 commit comments