Is it possible to create a type alias that has trait bounds on a generic type for a function?
Asked Answered
P

2

17

This code:

pub type Foo<T: Read> = fn(bar: T);

yields error E0122 (in newer versions of Rust, it is only a warning):

An attempt was made to add a generic constraint to a type alias. This constraint is entirely ignored. For backwards compatibility, Rust still allows this with a warning. Consider the example below:

trait Foo {}

type MyType<R: Foo> = (R, ());

fn main() {
    let t: MyType<u32>;
}

We're able to declare a variable of type MyType<u32>, despite the fact that u32 does not implement Foo. As a result, one should avoid using generic constraints in concert with type aliases.

Is it possible to create a type alias that contains trait requirements on a function pointer? Obviously the compiler is telling me no for types, but didn't know if there was another option for functions that I wasn't thinking of.

Pippa answered 17/6, 2016 at 0:14 Comment(1)
This doesn't seem to be possible, as the error says. Experimenting with Fn(T) as well didn't get me anywhere.Stancil
P
8

At this time, it does not seem to be possible and no workarounds exist.

Pippa answered 20/6, 2016 at 18:14 Comment(0)
D
8

For anyone still curious about this as of Rust 1.47.0 it is still not possible but it looks like you get a nice little warning message with a description and suggested alternative. e.g.

pub type PublishQueue<T: From<Message>> = (tokio::sync::mpsc::Sender<T>);

yields

note: `#[warn(type_alias_bounds)]` on by default
help: the bound will not be checked when the type alias is used, and should be removed
|
| pub type PublishQueue<T> = sync::mpsc::Sender<T>;
|
Drexler answered 2/11, 2020 at 0:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.