< 返回版块

trait与泛型返回值的问题

类人界异 发表于

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-08T14:38:16.174371

参考实现:

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

laizy 2018-04-08T14:43:35.570465
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()
    }
}
作者 类人界异 2018-04-10T08:15:19.323728

正解

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

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

这样太麻烦了吧,而且基础类型貌似都没有实现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-11T09:51:56.338841

任何类型实际上都实现了到自己的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

1 共 5 评论, 共 1 页