`generic_const_exprs` in trait bounds

⚓ Rust    📅 2025-08-13    👤 surdeus    👁️ 3      

surdeus

The feature generic_const_exprs works as expected, but it seems it can limit functions, but not trait bounds.

#![feature(generic_const_exprs)]
#![allow(incomplete_features)]

#[derive(Copy, Clone, Debug)]
struct A<const N: usize>([u64; N]);

struct Condition<const U: bool>;

trait IsTrue {}
impl IsTrue for Condition<true> {}

impl<const N: usize, const M: usize> From<A<M>> for A<N> 
    where 
        Condition<{N > M}>: IsTrue
{
    fn from(v: A::<M>) -> Self {
        let mut out = [0; N];
        
        for i in 0..M {
            out[i] = v.0[i];
        }
        
        Self(out)
    }
}

fn main() {
    let a = A([1, 2, 3]);
    println!("{a:?}");
    
    let b: A::<4> = a.into();
    println!("{b:?}");
    
    let c: A::<5> = a.into();
    println!("{c:?}");
}

produces an error:

Compiling playground v0.0.1 (/playground)
error[E0119]: conflicting implementations of trait From<A<_>> for type A<_>
--> src/main.rs:12:1
|
12 | / impl<const N: usize, const M: usize> From<A> for A
13 | | where
14 | | Condition<{N > M}>: IsTrue
| |__________________________________^
|
= note: conflicting implementation in crate core:
- impl From for T;

For more information about this error, try rustc --explain E0119.
error: could not compile playground (bin "playground") due to 1 previous error

How can this problem be solved without explicit specialization for all possible N and M?

1 post - 1 participant

Read full topic

🏷️ Rust_feed