< 返回版块

类人界异 发表于 2018-04-08 16:18

Tags:trait,mul,泛型

trait Area<T>{
    fn area(&self)->T;
}

struct Rect<T>{
    x_side:T,
    y_side:T,
}

struct Circle<T>{
    r:T,
}

impl<T:std::ops::Mul> Area<T> for Rect<T>{
    fn area(&self)->T{
        self.x_side*self.y_side
    }
}

代码如上,在为Rect实现Area时,需要x_side和y_side做乘法,所以T bond 了std::ops::Mul,可是Mul内部的OutPut怎么规定?

评论区

写评论
套路小迷糊 2018-04-11 17:51

任何类型实际上都实现了到自己的Into

struct Foo(u8);

fn bar<T: Into<Foo>>(x: T){
    println!("{:?}", x.into().0);
}

fn main() {
    bar(Foo(0));
}

@类人界异 这样太麻烦了吧,而且基础类型貌似都没有实现Into trait

@套路小迷糊 参考实现: impl Area for Rect where T: std::ops::Mul + Copy, ::Output: Into, { fn area(&self) -> T { (self.x_side * self.y_side).into() } } 实现思路: http://mp.weixin.qq.com/s/L5-xN3Ll09NdE-CEKgatMg

套路小迷糊 2018-04-11 17:49

任何类型实际上都实现了到自己的Into

@类人界异 这样太麻烦了吧,而且基础类型貌似都没有实现Into trait

@套路小迷糊 参考实现: impl Area for Rect where T: std::ops::Mul + Copy, ::Output: Into, { fn area(&self) -> T { (self.x_side * self.y_side).into() } } 实现思路: http://mp.weixin.qq.com/s/L5-xN3Ll09NdE-CEKgatMg

作者 类人界异 2018-04-10 16:24

这样太麻烦了吧,而且基础类型貌似都没有实现Into trait

@套路小迷糊 参考实现: impl Area for Rect where T: std::ops::Mul + Copy, ::Output: Into, { fn area(&self) -> T { (self.x_side * self.y_side).into() } }

实现思路: http://mp.weixin.qq.com/s/L5-xN3Ll09NdE-CEKgatMg

作者 类人界异 2018-04-10 16:15

正解

@laizy impl<T: std::ops::Mul<Output=T> + Clone > Area for Rect { fn area(&self)->T{ self.x_side.clone()*self.y_side.clone() } }

laizy 2018-04-08 22:43
impl<T: std::ops::Mul<Output=T> + Clone > Area<T> for Rect<T> {
    fn area(&self)->T{
        self.x_side.clone()*self.y_side.clone()
    }
}
laizy 2018-04-08 22:42
impl<T: std::ops::Mul<Output=T> + Clone > Area<T> for Rect<T> {
    fn area(self)->T{
        self.x_side.clone()*self.y_side
    }
}
laizy 2018-04-08 22:42

impl<T: std::ops::Mul<Output=T> + Clone > Area for Rect { fn area(self)->T{ self.x_side.clone()*self.y_side } }

套路小迷糊 2018-04-08 22:38

参考实现:

impl<T> Area<T> for Rect<T>
where
    T: std::ops::Mul + Copy,
    <T as std::ops::Mul>::Output: Into<T>,
{
    fn area(&self) -> T {
        (self.x_side * self.y_side).into()
    }
}

实现思路:
http://mp.weixin.qq.com/s/L5-xN3Ll09NdE-CEKgatMg

套路小迷糊 2018-04-08 21:39
impl<T> Area<T> for Rect<T>
where
    T: std::ops::Mul + Clone,
    <T as std::ops::Mul>::Output: Into<T>,
{
    fn area(&self) -> T {
        (self.x_side.clone() * self.y_side.clone()).into()
    }
}

套路小迷糊 2018-04-08 21:39

impl Area for Rect where T: std::ops::Mul + Clone, ::Output: Into, { fn area(&self) -> T { (self.x_side.clone() * self.y_side.clone()).into() } }

1 共 10 条评论, 1 页