5

I am trying to use associated constants as a condition in an if-expression to initialize another constant. I think that this should work, as I can use the associated constants directly to initialize some other constant, so it is applicable in a const context and the if expression does not depend on any other values.

trait C {
    const c: i32;
}

trait StaticAssert<T1: C, T2: C> {
    const canUseAssociatedConst: i32 = T1::c;
    const canCompareAssociatedConst: bool = T1::c == T2::c;

    const check: i32 = if T1::c == T2::c { 1 } else { 0 };
}

When I compile this, I get an error:

error[E0019]: constant contains unimplemented expression type
 --> src/lib.rs:9:24
  |
9 |     const check: i32 = if T1::c == T2::c { 1 } else { 0 };
  |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

I am not sure what the compiler wants to tell me. I've added i32 suffixes to enforce that the literals are actually i32 values to prevent any issues from different types in the branches, but this did not help either.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Jens
  • 9,058
  • 2
  • 26
  • 43

1 Answers1

5

As far as I know, if and others are not (yet) supported in const contexts.

However, often you can acchieve a similar effect along the lines of the following:

trait C {
    const c: i32;        
}

trait StaticAssert<T1:C, T2:C> {
    const canUseAssociatedConst: i32 = T1::c;
    const canCompareAssociatedConst: bool = T1::c == T2::c;

    const check: i32 = (T1::c == T2::c) as i32;
}
phimuemue
  • 34,669
  • 9
  • 84
  • 115
  • A `const fn` with an if-expression gives a better error message: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=156bb6f19dc28b5f554c2df2d24fcd67. However, functions without ifs are not very usefull... The class of functions that can be represented without conditions is rather small. – Jens Jan 04 '19 at 15:10
  • 6
    @Jens A slightly more general hack is to use `[expr1, expr2][condition as usize]` to select between two const expressions based on a condition. – Sven Marnach Jan 04 '19 at 15:13