【发布时间】:2015-05-21 01:43:28
【问题描述】:
我想要一个函数,它接受可以转换为我的特定类型的各种类型。在类似的情况下,我会使用std::convert::Into(或std::convert::From):
pub struct MyThing;
impl<'a> Into<MyThing> for &'a str {
fn into(self) -> MyThing {
MyThing
}
}
fn main() {}
作为一个额外的问题,在我的具体情况下,转换可能会失败。通常,我会使用Result 来表示可能失败的操作。将两个概念结合在一起:
pub struct MyThing;
pub struct Error;
impl<'a> Into<Result<MyThing, Error>> for &'a str {
fn into(self) -> Result<MyThing, Error> {
if self.len() % 2 == 0 {
Ok(MyThing)
} else {
Err(Error)
}
}
}
fn main() {}
不幸的是,这似乎违反了连贯性规则:
error: the impl does not reference any types defined in this crate;
only traits defined in the current crate can be implemented for
arbitrary types [E0117]
我发现我可以创建自己的特定特征:
struct MyThing;
struct Error;
trait IntoMyThing {
fn into(self) -> Result<MyThing, Error>;
}
impl<'a> IntoMyThing for &'a str {
fn into(self) -> Result<MyThing, Error> {
if self.len() % 2 == 0 {
Ok(MyThing)
} else {
Err(Error)
}
}
}
fn main() {}
甚至是更通用的特征:
struct MyThing;
struct Error;
trait MaybeInto<T, E> {
fn into(self) -> Result<T, E>;
}
impl<'a> MaybeInto<MyThing, Error> for &'a str {
fn into(self) -> Result<MyThing, Error> {
if self.len() % 2 == 0 {
Ok(MyThing)
} else {
Err(Error)
}
}
}
fn main() {}
但是有没有办法重用标准库中的组件来实现我的目标?
【问题讨论】:
标签: rust