使用约束实现From / Into for struct

时间:2016-10-09 03:18:58

标签: rust traits

由于.max()f64不起作用,我正在编写一个ForceOrd结构,断言该参数不是NaN。预期用途类似于:

let m = xs.iter().map(|&x| ForceOrd(x)).max().unwrap().into();

但是,我无法使用错误编译Into trait实现:

conflicting implementations of trait `std::convert::Into<_>` for type `ForceOrd<_>`

代码(playground):

#[derive(PartialEq, PartialOrd)]
pub struct ForceOrd<X: PartialEq + PartialOrd>(pub X);
impl<X: PartialEq + PartialOrd> Eq for ForceOrd<X> { }
impl<X: PartialEq + PartialOrd> Ord for ForceOrd<X> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0.partial_cmp(&other.0).unwrap()
    }
}
/// doesn't work
impl<X: PartialEq + PartialOrd> Into<X> for ForceOrd<X> {
    fn into(x: Self) -> X { x.0 }
}
/// doesn't work either
impl<X: PartialEq + PartialOrd> From<ForceOrd<X>> for X {
    fn from(x: ForceOrd<X>) -> Self { x.0 }
}

1 个答案:

答案 0 :(得分:5)

您不能同时针对单一类型实施FromInto,例如,如果您impl From<ForceOrd<X>> for X,则无法impl Into<X> for ForceOrd<X>。你也只需要一个。由于IntoFrom的文档均声明:

From<T> for U implies Into<U> for T

您应该只使用From实施。您可以查看以下问题,了解一般选择的信息:When should I implement std::convert::From vs std::convert::Into?

修改:由于实施From并非(在这种情况下)只是移除impl Into,因此您可以看到f64如何实现{#[derive(PartialEq, PartialOrd, Debug)] pub struct ForceOrd<X: PartialEq + PartialOrd>(pub X); impl<X: PartialEq + PartialOrd> Eq for ForceOrd<X> { } impl<X: PartialEq + PartialOrd> Ord for ForceOrd<X> { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0.partial_cmp(&other.0).unwrap() } } impl<X: PartialEq + PartialOrd> From<X> for ForceOrd<X> { fn from(x: X) -> ForceOrd<X> { ForceOrd(x) } } fn main() { let xs = vec![1.1f64, 3.5, 2.2]; let max = xs.iter().map(|&f| <ForceOrd<f64>>::from(f)).max().unwrap(); println!("{:?}", max); // prints "ForceOrd(3.5)" } 1}}:

impl<X: PartialEq + PartialOrd> From<ForceOrd<X>> for X

不幸的是,我担心这是你能得到的;你无法实现:

<f64>::from(xs.iter().map(|&f| <ForceOrd<f64>>::from(f)).max().unwrap())

能够做最后的

f64

因为openScreenshot(imageFile)不是此箱子的本地。您可以在this very detailed blog entry by Niko Matsakis中详细了解此限制,并参阅this question in StackOverflow