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

前端 未结 4 1082
有刺的猬
有刺的猬 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:15

    Fairly new to Rust, so may need checking.

    You could parametrise over the return type. This has limits, but they're less restrictive than simply returning Self.

    trait A where T: A {
        fn new() -> T;
    }
    
    // return a Self type
    struct St1;
    impl A for St1 {
        fn new() -> St1 { St1 }
    }
    
    // return a different type
    struct St2;
    impl A for St2 {
        fn new() -> St1 { St1 }
    }
    
    // won't compile as u32 doesn't implement A
    struct St3;
    impl A for St3 {
        fn new() -> u32 { 0 }
    }
    

    The limit in this case is that you can only return a type T that implements A. Here, St1 implements A, so it's OK for St2 to impl A. However, it wouldn't work with, for example,

    impl A for St2 ...
    impl A for St1 ...
    

    For that you'd need to restrict the types further, with e.g.

    trait A where U: A, T: A {
        fn new() -> T;
    }
    

    but I'm struggling to get my head round this last one.

提交回复
热议问题