I'm just learning Rust, so maybe I just didn't get some concepts correctly.
I have a trait with some implementations:
trait Abstract {
fn name(&self) -> &str;
}
struct Foo {}
struct Bar {}
struct Baz {}
impl Abstract for Foo {
fn name(&self) -> &str { "foo" }
}
impl Abstract for Bar {
fn name(&self) -> &str { "bar" }
}
impl Abstract for Baz {
fn name(&self) -> &str { "baz" }
}
I want to add a static method to this trait to create some standard implementation by name:
trait Abstract {
fn new(name: &str) -> Self {
match name {
"foo" => Foo{},
"bar" => Bar{},
"baz" => Baz{},
}
}
fn name(&self) -> &str;
}
But this code doesn't compile because:
6 | fn new(name: &str) -> Self {
| ^^^^ doesn't have a size known at compile-time
I tried to use return fn new(name: &str) -> impl Abstract and
fn new<T: Abstract>(name: &str) -> T - but these variants doesn't work too with another errors.
What is the correct way exist of creating factory method for trait in Rust?