简体   繁体   中英

How can I implement a function that returns a generic constrained by an integral type?

How can I implement a function such as the following, where T is an integral type?

fn get_vec<T>() -> Vec<T>
{
    let vec: Vec<T> = Vec::new();
    let n: i32 = 5;
    let n_as_t = n as T;
    vec.push(n_as_t);
    vec
}

The problem is that generics are type-checked prior to being expanded; this means that the compiler must verify that n as T (where n is an i32 ) is valid for all possible T . It isn't.

What you want is to, using a trait, constrain T to types which can be cast from an i32 . Somewhat tragically, this trait does not exist.

The closest analog is probably std::convert::From , but it doesn't implement such basic conversions and you can't provide them yourself. There used to be some traits that dealt in converting to/from primitive integer types, but I believe they were removed prior to the 1.0 cleanup.

At which point, you're basically on your own. You need to roll a trait that expresses this conversion, then implement it for the types you care about. So, you could use a trait such as:

trait FromI32 {
    fn from_i32(v: i32) -> Self;
}

then change the function to use <T: FromI32> and FromI32::from_i32(n) instead of n as T .

If there are more than a few types for which you want to implement said trait, a simple macro should cut down on the repetition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM