BallpointBen
BallpointBen

Reputation: 13750

Specify type of numeric literal as `type` alias

I would like to write the equivalent of 2_u32, 7_i64, etc but where the numeric type is given by a type alias. e.g.,

type Number = u32;

fn main() {
    let a = 1_Number; // invalid syntax
    let b = 1_u32; // works, but isn't tied to `Number`
    let c = 1 as Number; // equivalent to `1_i32 as Number`, which is not what I want
    let d = Number::from(1) // requires `Number: From<i32>`, again not what I want
    let e = ???
}

So, is there a way to write “variable” numeric literal, whose type is that of a given type alias?

Upvotes: 1

Views: 237

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 70990

You can use type annotations:

let a: Number = 1;

Or, for inside nested expressions, you can create a macro to do that for you:

macro_rules! force_type {
    ($v:expr, $ty:ty $(,)?) => {{
        let v: $ty = $v;
        v
    }};
}

foo(force_type!(1, Number));

If you can limit yourself to literals, you can use a nicer syntax:

macro_rules! n {
    ($v:literal : $ty:ty) => {{
        let v: $ty = $v;
        v
    }}
}

foo(n!(1: Number));

Upvotes: 2

Related Questions