Question about type alias and use keyword

In my code, I want easily switch between floating point number precision, so I do the following

type scalar = f64;

afterward, I want to use the INFINITY in std::f64. Then it becomes

use std::f64;
type scalar = f64;

then the problem comes with scalar::INFINITY: no associated item named INFINITY found for type f64 in the current scope. But the f64::INFINITY is accessible.

How can I use scalar::INFINITY in my code?

I think the problem is that std::f64 is a module but f64 is a primitive type. All the constants are in the module and not the primitive so the type alias doesn't know about them.

I don't know the best way to work around this. Two options that come to mind are you could use a separate const (e,g, SCALAR_INFINITY) or use a module to namespace it all, perhaps something like this:

pub mod scalar {
    use std::f64;
    pub type ty = f64;
    pub const INFINITY: f64 = f64::INFINITY;
}
let n: scalar::ty = scalar::INFINIITY;

Try use ... as ...

1 Like

These are not elegant at all...

and I resorts to use num_traits, from which I can use scalar::infinity() and other utility functions

I'm glad you found a solution you like, but I'm curious what makes that more attractive than use ... as ...?

There's a historical effect here from Rust not having associated consts in inherent impls back in the day.

You'll notice that mod-const std::time::UNIX_EPOCH has now also been added as impl-const std::time::SystemTime::UNIX_EPOCH, so you might consider starting a discussion with the libs team about whether doing something similar with the floating point constants would be good.