Creating Type Aliase with general type

We can create type-aliase as below:

type Kilometers = i32;

Can we create such type with generaic parameter, like:

use std::ops::Mul;
type Kilometers = T where T: Mul;

This technically compiles:

type A<T: Mul> = T;

But the compiler produces a warning: bounds on generic parameters are not enforced in type aliases.

Even if it was possible, it wouldn’t be very useful to add a bound to a type alias. Yes, you can do this for structures:

struct MyStruct<T: Mul>(T);

But this is considered bad practice. It’s generally better to add bounds to the implementations instead:

struct MyStruct<T>(T);
impl <T: Mul> MyStruct<T> { ... }

You can do the same for type aliases.

If you want to re-use your type bounds in multiple places without repeating it everywhere, a common pattern is to make a trait:

trait MyTrait: Mul + Add + Sized {}
impl<T: Mul + Add> MyTrait for T {}
fn my_func<T: MyTrait>(value: T) {}
1 Like

Type aliases don't create a new type. They just add another name to refer to the same type.

In your case i32 and Kilometers are exactly the same type in every way, so you don't get any extra type safety, and you will be limited in what you're allowed to implement on i32 (it doesn't matter if you try to do it via another aliased name).

1 Like