2

I have a question about defining types in Rust. As an example, I have defined two types:

pub type Distance = f32;
pub type Cost = f32;

My reason for defining these types, instead of using f32 directly, is for clarity in the code and to try to catch whenever I make a mistake/think incorrectly.

So for example, I have a function.

pub fn calculate_cost_from_distance(distance : Distance) -> Cost

However, I can pass a Cost into that function without any complaints from the compiler (since they are both really f32).

So, my question is, is there any way to force the compiler to view types like these as different and throw an error?

If possible, it would be nice to not have to create completely custom types for Distance and Cost, redefining all operators and such, since I want them to behave just like floats when working with them.

Any thoughts or other ways to approach this is very much appreciated!

1 Answers1

6

You want to be using newtype instead of Type Aliasing (type) i.e.

pub struct  Distance(f32);
pub struct  Cost(f32);

see https://doc.rust-lang.org/rust-by-example/generics/new_types.html

SamBob
  • 849
  • 6
  • 17