Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve associated constant item CTFE timing section #1147

Merged
merged 3 commits into from
Feb 8, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions src/items/associated-items.md
Original file line number Diff line number Diff line change
Expand Up @@ -293,22 +293,35 @@ type that the definition has to implement.
An *associated constant definition* defines a constant associated with a
type. It is written the same as a [constant item].

Unlike [free] constants, associated constant definitions undergo
[constant evaluation] only when referenced.
Associated constant definitions undergo [constant evaluation] only when
referenced. Further, definitions that include [generic parameters] are
evaluated after monomorphization.

```rust
```rust,compile_fail
struct Struct;
struct GenericStruct<const ID: i32>;

impl Struct {
const ID: i32 = 1;
// Definition not immediately evaluated
const PANIC: () = panic!("compile-time panic");
}

impl<const ID: i32> GenericStruct<ID> {
// Definition not immediately evaluated
const NON_ZERO: () = if ID == 0 {
panic!("contradiction")
};
}

fn main() {
assert_eq!(1, Struct::ID);
// Referencing Struct::PANIC causes compilation error
// let _ = Struct::PANIC;
let _ = Struct::PANIC;

// Fine, ID is not 0
let _ = GenericStruct::<1>::NON_ZERO;

// Compilation error from evaluating NON_ZERO with ID=0
let _ = GenericStruct::<0>::NON_ZERO;
}
```

Expand Down Expand Up @@ -381,5 +394,4 @@ fn main() {
[regular function parameters]: functions.md#attributes-on-function-parameters
[generic parameters]: generics.md
[where clauses]: generics.md#where-clauses
[free]: ../glossary.md#free-item
[constant evaluation]: ../const_eval.md