jjmark15
jjmark15

Reputation: 173

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>>()
}

Upvotes: 2

Views: 1629

Answers (1)

Optimistic Peach
Optimistic Peach

Reputation: 4318

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.

Upvotes: 1

Related Questions