我有一个自定义类型pub struct Foo,我希望能够说字符串可以转换为Foo类型.我正在努力impl<'a> Into<Foo> for &'a str,但我从这个答案中知道我不能这样做.我还有其他选择吗?
对于上下文,我正在尝试做类似的事情
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 }
}
Run Code Online (Sandbox Code Playgroud)
正如克里斯摩根指出的那样,FromStr是一种选择,From<&str>也是另一种选择。后者也会为您提供Into<Foo>for的内置实现&str(因为有一个全面的 impl of Into<U> For T where U: From<T>)。