Generics: no field `my_field` on type `&T (error[E0609])

Hi,

I have a free standing function inside a mode that I want to accept some generics:

fn my_generics_function<T>( param1: &T, param2: &T) {

and in the same module it is called:

my_generics_function::<CStruct1>(&param1, &param2);

The problem :
the compiler compains that param of type T doesn't have field0;

error[E0609]: no field `field0` on type `&T`

If I make the function non generic:

fn my_generics_function( param1: &CStruct1, param2: &CStruct1) {

it works.

I also tried
my_generics_function(&param1, &param2);
with the same result.

param1 and param2 are of type:

Simplified code (changed names and all for a better focus):

enum Enum0{
 VALUE0,
 VALUE1,
}

pub(crate) struct CStruct1 {
        pub(crate) field0:  Enum0,
        ...
}

fn my_generics_function<T>( param1: &T, param2: &T) {
     ...
     param1.field0 // <- error here
     ...

}

fn other_function(){
    ...
    let param1 : CStruct1;
    ...
    my_generics_function(&param1, &param2); // or my_generics_function::<CStruct1>(&param1, &param2);
    ...
}

I desperately tried #![feature(min_specialization)] in my lib.rs with the same result.

My current workaround is to manually copy/paste code with the specific type.
So not a show stopper; But if there is a better way, usable right now in the nightly compiler, I take it.

Thanks!

In Rust, you can only make use of generic parameters in ways specified by trait bounds; your function body must work for any and every type that meets those bounds.

It's compile time error to have a function body that doesn't comply, in contrast to a compile or runtime error to can the function with a type incompatible with the body. It's not a syntactic macro system.

You have no bounds,[1] so there's almost nothing you can do with the arguments.

Even if you add bounds, traits don't support required fields. You'll need getters/setters, or maybe generics isn't the right solution for your use case.


  1. except an implicit Sized bound â†Šī¸Ž

Ok got it, I will use macros then,

Thanks!

For future reference,
I solved my case using enums :+1:

Love this language :hugs:

1 Like