Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Specify the Unused Return Type of a Generic Function?

I have a function which returns a struct with PhantomData, where I discard the result. An example of this looks like:

use std::marker::PhantomData;

struct Foo<T> {
    marker: PhantomData<T>,
}

fn foo<T>() -> Foo<T> {
    // something useful
    Foo {
        marker: PhantomData,
    }
}

fn main() {
    let _ = foo();
}

This code produces this error:

error[E0282]: type annotations needed for `Foo<T>`
  --> src/main.rs:15:9
   |
15 |     let _ = foo();
   |         ^
   |
help: consider giving this pattern a type, where the type for type parameter `T` is specified
   |
15 |     let _: Foo<T> = foo();
   |          ++++++++

What is the best type to assign here? (does it not matter?)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Usually for unused type parameters one would use () also known as unit.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading