Rust "lazy" generic instantiation?

Consider this:

pub struct Broken<T> {
  a: T::A,

This code does not compile because we might pass it a type T that does not contain a ::A.

However, is it possible to delay this check ? I.e. I would like a world here Broken<i32> results in a compile error, but the above Broken can be defined w/o an error.

Is there a way to mimic this ?

There's not even a way to be generic over the trait in which A is defined. So you need to restrict T to some specific A-containing trait.

1 Like

no, you cannot do it with a unconstraint generic type (i.e. duck-typeing). rust generic is not like C++ template, which only checks for well-formed syntactical constructs. rust always need to type check a struct definition locally.

you must explicitly constrain the generic type parameter with traits. it's a type level constraint, not syntactical. i.e. you have to mark the supported type with correct trait.

put trait HasA {
    type A;
pub struct Broken<T: HasA> {
    a: T::A,

// error: i32 doesn't implement `HasA`
let x: Broken<i32>;

// `Foo` is accepted, because `HasA`
struct Foo;
impl HasA for Foo {
    type A = ...;
let x: Broken<Foo>;

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.