简体   繁体   English

如何实现泛型类型的特征?

[英]How to implement a trait for generic type?

In Rust what is the proper way of implementing traits for a generic type?在 Rust 中,为泛型类型实现特征的正确方法是什么? I'm expecting my Vector to consist of integers or floats.我希望我的向量由整数或浮点数组成。 Irregardless of the type I want get_magnitude() to output f64.不管我想要 get_magnitude() 到 output f64 的类型是什么。 How do I get powi() and sqrt() to work?如何让 powi() 和 sqrt() 工作? Any workarounds?任何解决方法? I'm stuck我被困住了

pub struct Vector<T> {
    i: T,
    j: T,
    k: T,
}

impl<T> Vector<T> {
    fn new(i: T, j: T, k: T) -> Vector<T> {
        Vector {
            i,
            j,
            k,
        }
    }
}

impl<T> Vector<T> {
    fn get_magnitude(&self) -> f64 {
        (self.i.powi(2) + self.j.powi(2) + self.k.powi(2)).sqrt()
    }
}

[https://www.codewars.com/kata/58ee4962dc4f81d6f400001c/rust][1] [https://www.codewars.com/kata/58ee4962dc4f81d6f400001c/rust][1]

You can have get_magnitide() constrained to only work when T is applicable.您可以将get_magnitide()限制为仅在T适用时才起作用。 And instead of constraining that T has a powi() , I'd recommend just converting them to f64 initially and doing the math from there.而不是限制T有一个powi() ,我建议最初将它们转换为f64并从那里进行数学运算。

You can use the AsPrimitive<f64> trait from the num crate for that:您可以使用num crate 中的AsPrimitive<f64>特征:

use num::cast::AsPrimitive; // 0.4.0

pub struct Vector<T> {
    i: T,
    j: T,
    k: T,
}

impl<T> Vector<T> {
    fn new(i: T, j: T, k: T) -> Vector<T> {
        Vector { i, j, k }
    }
}

impl<T> Vector<T> {
    fn get_magnitude(&self) -> f64
    where
        T: AsPrimitive<f64>,
    {
        (self.i.as_().powi(2) + self.j.as_().powi(2) + self.k.as_().powi(2)).sqrt()
    }
}

You may also constrain the whole Vector struct to only work when T is a number via the Num trait:您还可以通过Num特征将整个Vector结构限制为仅在T是数字时才起作用:

use num::Num; // 0.4.0

pub struct Vector<T>
where
    T: Num
{
    i: T,
    j: T,
    k: T,
}

But you will still need the constraint on get_magnitude() since you're enforcing that it returns a f64 .但是你仍然需要对get_magnitude()的约束,因为你强制它返回一个f64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM