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
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.