Can I qualify primitve literals in a consistent way?

Since an Option<T> takes a type parameter, I can qualify the type of anonymous, ambiguous values like so:

f(None::<u8>);

For numeric literals, I can do:

f(1i32);

For slices it's:

f(&[] as &[i32]);

My question is: is there a consistent way to qualify, rather than cast, all primitive literals including arrays and slices?

Sure, send them through a type-annotated let.

f({ let x: Option<u8> = None; x });
f({ let x: i32 = 1; x });
f({ let x: &[i32] = &[]; x });
2 Likes

It's ugly, but you can use std::convert::identity:

use std::convert::identity;
f(identity::<Option<u8>>(None));
f(identity::<i32>(1));
f(identity::<&[i32]>(&[]));

There's also an unstable feature called type ascriptions that allows you to do:

f(None: Option<u8>);
f(1: i32);
f(&[]: &[i32]);

Unfortunately it's currently stalled.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.