Z
Z
ziplane2019-08-28 18:14:57
Rust
ziplane, 2019-08-28 18:14:57

How to restrict type T to primitive types f32 and f64?

in short then

impl<T> Compute<T> for Astra 
    where T:f32 +f64
{ 
    fn compute(&self, input: &mut Matrix<T>) -> Matrix<T> {
          // Что то делать 
    }
}

I need to use methods f64 and f32, but due to the fact that the type <T>is unknown, it (the compiler)
swears that it is impossible to call the method without knowing who this one <T>
is. I can’t use it like this (below). Since the Astra structure is a marker and it is required.
impl<T> Compute<T> for f64
{ 
    fn compute(&self, input: &mut Matrix<T>) -> Matrix<T> {
          // Что то делать 
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2019-08-28
@bingo347

You can restrict a generic type to only traits.
What do you want to do? What methods f32 and f64 do you need?
Perhaps these methods are already implemented in the traits of the standard library - then you need to limit them to the amount.
Another option is to make your own trait, restrict the generic type to it, implement this trait for f32 and f64
Implementation should represent wrappers over the necessary actions
UPD: if you need a generic restriction, to use the exp method for f32 and f64: Trait
contract for the exp method:

trait Exp {
    fn exp(self) -> Self;
}

impl Exp for f32 {
    fn exp(self) -> Self {
        <f32>::exp(self)
    }
}

impl Exp for f64 {
    fn exp(self) -> Self {
        <f64>::exp(self)
    }
}

you can also use the following crate:
https://crates.io/crates/num

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question