Is it possible to use `impl Trait` as a function's return type in a trait definition?

前端 未结 4 1083
有刺的猬
有刺的猬 2020-11-28 15:45

Is it at all possible to define functions inside of traits as having impl Trait return types? I want to create a trait that can be implemented by multiple stru

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 16:19

    You can get something similar even in the case where it's not returning Self by using an associated type and explicitly naming the return type:

    trait B {}
    struct C;
    
    impl B for C {}
    
    trait A {
        type FReturn: B;
        fn f() -> Self::FReturn;
    }
    
    struct Person;
    
    impl A for Person {
        type FReturn = C;
        fn f() -> C {
            C
        }
    }
    

提交回复
热议问题