Trait::const associated type error


#1

Hi,

Since Rust still has no alowed consts in generics I am considering 2 workarounds, but both of them fails with weird error, here they are:

use std::marker::PhantomData;

trait Test: Sized {
    const Size: usize;
}

struct RingQueue<S: Test> {
    arr: [u8; <S as Test>::Size],
    _m: PhantomData<S>,
}

impl<S> RingQueue<S: Test> {
    pub fn new() -> Self {
        Self {
            arr: [0; <S as Test>::Size],
            _m: Default::default(),
        }
    }
}

struct S16; 
impl Test for S16 {
    const Size: usize = 16;
}

fn main() {
    RingQueue::<S16>::new();
    println!("Test");
}

I have next error message from compiler:

error[E0277]: the trait bound `S: Test` is not satisfied
  --> src/main.rs:11:15
   |
11 |     arr: [u8; <S as Test>::Size],
   |               ^^^^^^^^^^^^^^^^^ the trait `Test` is not implemented for `S`
   |
   = help: consider adding a `where S: Test` bound

Why such message, it is clear that I’ve added S: Test bound for struct definition and impl?

Other option is to use mem::size_of:

use std::marker::PhantomData;
use std::mem;

struct RingQueue<S: Sized> {
    arr: [u8; mem::size_of::<S>()],
    _m: PhantomData<S>,
}

impl<S: Sized> RingQueue<S> {
    pub fn new() -> Self {
        Self {
            arr: [0; mem::size_of::<S>()],
            _m: Default::default(),
        }
    }
}

fn main() {
    RingQueue::<[u8; 16]>::new();
    println!("Hi");
}

but it also fails, with similar error:

error[E0277]: the size for values of type `S` cannot be known at compilation time
 --> src/main.rs:5:15
  |
5 |     arr: [u8; mem::size_of::<S>()],
  |               ^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `S`
  = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = help: consider adding a `where S: std::marker::Sized` bound
  = note: required by `std::mem::size_of`

Any clue what I did wrong, or how else i can be done without an error?


#2

This is a known issue.