Reply to post: Re: Error Types

Linus Torvalds says Rust is coming to the Linux kernel 'real soon now'

birkett83

Re: Error Types

The rust compiler can *absolutely* help you with that.

You can define zero-sized types for MilesPerHour, MetresPerSecond, SmootsPerFortnight etc and then give your velocity struct a generic parameter for the unit. The compiler will then give you a type error if you try to use a Velocity<MilesPerHour> where it was expecting a Velocity<MetresPerSecond>.

Since the units are zero-sized types, they're not actually stored memory when the program is run, they exist only at compile time. This is an example of what rust developers call "zero-cost abstractions".

The ability to enforce these kinds of safety properties is a pretty neat application of Rust's strong type system and it's considered good practice in Rust. Have a look at the Euclid crate for an example of this pattern being used in practice.

Cool huh?

POST COMMENT House rules

Not a member of The Register? Create a new account here.

  • Enter your comment

  • Add an icon

Anonymous cowards cannot choose their icon