Generic Type Questions

Hey. How do I implement something like this:

pub struct Foo<T1> {...}

pub struct Bar {
	x:u64,
}

impl Bar {
 pub fn Tar(&self, ...) -> Foo<T1> {...}

}

Of course this does not work. But I don't know how to implement something like this. Simply using

pub struct Bar<T1> {
	x:u64,
}

impl<T1> Bar>T1> {
 pub fn Tar(&self, ...) -> Foo<T1> {...}

}

gives a compiler error of unused parameter T1 ...

You can add the parameter on the function itself:

impl Bar {
    pub fn tar<T1>(&self, ...) -> Foo<T1> {...}
}

Also, please try to use proper indentation. You might want to use backtics instead of four spaces for marking code blocks.

1 Like

Depending on your use case, In addition to @alice's solution you may want to add it to the struct as PhantomData.

struct Bar<T> {
    x: u64,
    _phantom: PhantomData<T>,
}
1 Like

If you show what your actual problem is, we can give some more relevant help. In most cases where you have a unused generic type parameter, it points at a deeper reason that you don't actually need that generic parameter, and adding PhantomData usually isn't what you want.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.