我有一个自定义类型pub struct Foo
,我希望能够说字符串可以转换为Foo
类型。我正在尝试impl<'a> Into<Foo> for &'a str
,但我从this answer知道我不能这样做。我还有其他选择吗?
对于上下文,我正在尝试做类似
的事情trait Foo {
type ArgType;
fn new<I: Into<Self::ArgType>>(arg: I) -> Self;
}
struct MyType;
impl Into<MyType> for str {
fn into(self) -> MyType { MyType }
}
struct Bar;
impl Foo for Bar {
type ArgType = MyType;
fn new<I: Into<MyType>>(arg: I) -> Bar { Bar }
}
答案 0 :(得分:4)
正如Chris Morgan所说,FromStr
是一种选择,From<&str>
将是另一种选择。后者将为Into<Foo>
提供&str
的内置实现(因为有Into<U> For T where U: From<T>
的全面内容。)