Possible to create new primitive types or alias an existing type and add new functions?


I would expect something like:

type MyU32 = u32;
impl MyU32 {
  pub fn only_works_on_my_u32 {

I would avoid making 'MyU32' as a struct, which would add one more layer of indirection.

If it is not possible to do so at user level, is there an easy way to achieve this by hacking rustc?


The layer of indirection is virtual, not real, it's just a different name.

You can do this with a tuple struct rather than a type alias:

struct MyU32(u32);

impl MyU32 {
1 Like

You can also create a trait and implement it on u32 to add new functions on the primitive type, unless you really do need a separate type.

If you do use a tuple struct to implement this, I would suggest looking at the newtype_derive crate to allow that tuple struct to have the (almost) same behaviors as the type you are wrapping.