What is a concise way to inform the compiler of the specifc type with multiple implementations of a generic trait?

前端 未结 1 1599
余生分开走
余生分开走 2020-12-22 04:03

I\'ve come across an odd type inference problem that has me scratching my head a bit.

I\'m implementing a generic trait on a struct for multiple types. I started wit

相关标签:
1条回答
  • 2020-12-22 04:47

    Pass the type parameter to the trait using a turbofish (::<>):

    assert_eq!("asd", Foo::<&str>::foo(&bar));
    

    You could also use fully-qualified syntax to disambiguate which trait the method belongs to:

    // This is "type-qualified" and equivalent to `Foo::<&str>::foo(&bar)`
    assert_eq!("asd", <_ as Foo<&str>>::foo(&bar));
    
    // This is "fully qualified"
    assert_eq!("asd", <Bar as Foo<&str>>::foo(&bar));
    
    0 讨论(0)
提交回复
热议问题