Skip to content

Commit 37e3c15

Browse files
committed
Use generics in associated const CTFE timing example
This makes the example a bit bigger, but makes the reason why constants don't immediately undergo CTFE more conspicuous. When there is computation in the definition that use generic parameters, there is not enough information to fully evaluate the definition eagerly. I made it a `compile_fail` example so the run button on the page gives reader useful outputs.
1 parent d0b33a2 commit 37e3c15

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/items/associated-items.md

+16-4
Original file line numberDiff line numberDiff line change
@@ -297,19 +297,31 @@ Associated constant definitions undergo [constant evaluation] only when
297297
referenced. Further, definitions that include [generic parameters] are
298298
evaluated after monomorphization.
299299

300-
```rust
300+
```rust,compile_fail
301301
struct Struct;
302+
struct GenericStruct<const ID: i32>;
302303
303304
impl Struct {
304-
const ID: i32 = 1;
305305
// Definition not immediately evaluated
306306
const PANIC: () = panic!("compile-time panic");
307307
}
308308
309+
impl<const ID: i32> GenericStruct<ID> {
310+
// Definition not immediately evaluated
311+
const NON_ZERO: () = if ID == 0 {
312+
panic!("contradiction")
313+
};
314+
}
315+
309316
fn main() {
310-
assert_eq!(1, Struct::ID);
311317
// Referencing Struct::PANIC causes compilation error
312-
// let _ = Struct::PANIC;
318+
let _ = Struct::PANIC;
319+
320+
// Fine, ID is not 0
321+
let _ = GenericStruct::<1>::NON_ZERO;
322+
323+
// Compilation error from evaluating NON_ZERO with ID=0
324+
let _ = GenericStruct::<0>::NON_ZERO;
313325
}
314326
```
315327

0 commit comments

Comments
 (0)