简体   繁体   中英

is there a way to use a generic type alias as the generic type for a function in Rust

I want to be able to reuse a generic type alias as the generic type parameter for a couple of functions in Rust.

I have tried creating the following type alias following the syntax specified in the type alias rust docs :

type DebuggableFromStr<T: FromStr>
where
    <T as std::str::FromStr>::Err: std::fmt::Debug,
= T;

and would like to use it to replace the generic type definitions in the following function:

fn split_string_to_vec<T: FromStr>(s: String) -> Vec<T>
where
    <T as std::str::FromStr>::Err: std::fmt::Debug,
{
    s.split_whitespace()
        .map(|s| s.parse().unwrap())
        .collect::<Vec<T>>()
}

Nope since Rust doesn't enforce type bounds on type aliases. Your example is equivalent to this:

type DebuggableFromStr<T> = T;

Playground .

I don't believe it to be specifically documented anywhere but the compiler issues a warning if you try.

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