Search code examples
rustassociated-const

Associated constants in condition of constant ìf`-expression


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.


Solution

  • 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;
    }