Default trait implementation and PhantomData


Not sure if it is the right place to ask, but I’ll try :slight_smile:

I’m struggling with default trait implementation in type parameters of structure, which stores it as PhantomData.

Here is the snippet that illustrates the problem:

use std::marker::PhantomData;

trait Trait {}
struct Struct;

impl Trait for Struct {}

struct GenericStruct<T: Trait = Struct> {
    _marker: PhantomData<T>

impl<T: Trait> GenericStruct<T> {
    fn new() -> Self {
        GenericStruct {
            _marker: PhantomData

fn main() {

Rustc says that it cannot infer the type. Why so? And what can I do in this situation to not to have an API that asks the user to make explicit annotation for the default implementation of the trait I ship within the crate?




If you change the line in the main function to:


it compiles and runs. I think the GenericStruct by itself isn’t considered a concrete type, because it is generic, even though its only argument is defaulted. You need to use the “<>” syntax to actually instantiate a concrete GenericStruct<Struct>.



Yes I noticed this as well in one of my projects and to be honest I don’t really get why it is this way. Would there be any problem with allowing you to leave out the <> when all generic types have a default?



<GenericStruct>::new() is enough, the empty angle brackets are not necessary.
It moves GenericStruct from “value context” where inference is used to “type context” where defaults for type parameters are used.
Ideally, type inference should fall back to using default type parameters somehow, but it’s not clear how exactly this should be done (the recent iteration can be found in



Thanks! Unfortunately the <GenericStruct>::new() is not working in my case, I have 4 type parameters actually, one default and 3 infered from context.


closed #6

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