Implementing trait constant array that takes items that implement another trait

⚓ rust    📅 2025-06-11    👤 surdeus    👁️ 2      

surdeus

I'm getting a very strange error where the Rust compiler is telling me it's expecting a type parameter instead of a value. But when I change it to a type it says it expected a value instead of a type.

Full code:

trait Focusable {}

struct Example;

impl Focusable for Example {}

trait Indexable<Item: Focusable> {
    const INDICES: [Item; 1];
}

struct App;

impl <Item: Focusable> Indexable<Item> for App {
    const INDICES: [Item; 1] = [
        // Error here:
        // mismatched types
        // expected type parameter `Item`
        // found struct `Example`
        // (E0308)
        Example,
        // Obviously changing it to Item would not fix the error as it's not a value
    ];
}

fn main() {
    println!("Hello, world!");
}

Result of cargo run

cargo run
   Compiling temp v0.1.0 (/home/untitled1/rust-lernin/temp)
error[E0308]: mismatched types
  --> src/main.rs:15:9
   |
13 | impl <Item: Focusable> Indexable<Item> for App {
   |       ---- expected this type parameter
14 |     const INDICES: [Item; 1] = [
15 |         Example,
   |         ^^^^^^^ expected type parameter `Item`, found `Example`
   |
   = note: expected type parameter `Item`
                      found struct `Example`

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

When I change it to Item like it suggests, we can see clearly that it expects a value (as it should):

cargo run
   Compiling temp v0.1.0 (/home/untitled1/rust-lernin/temp)
error[E0423]: expected value, found type parameter `Item`
  --> src/main.rs:15:9
   |
13 | impl <Item: Focusable> Indexable<Item> for App {
   |       ---- found this type parameter
14 |     const INDICES: [Item; 1] = [
15 |         Item,
   |         ^^^^ not a value

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

3 posts - 2 participants

Read full topic

🏷️ rust_feed