【问题标题】:Is it possible to create a type alias that has trait bounds on a generic type for a function?是否可以为函数创建一个在泛型类型上具有特征边界的类型别名?
【发布时间】:2016-10-18 16:24:30
【问题描述】:

这段代码:

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

yields error E0122(在较新版本的 Rust 中,这只是一个警告):

尝试将通用约束添加到类型别名。这 约束被完全忽略。为了向后兼容,Rust 仍然允许这样做并发出警告。考虑下面的例子:

trait Foo {}

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

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

我们可以声明MyType&lt;u32&gt; 类型的变量,尽管事实上 u32 没有实现 Foo。因此,应避免使用 与类型别名一致的通用约束。

是否可以创建包含函数指针特征要求的类型别名?显然,编译器告诉我没有类型,但不知道是否还有其他我没有想到的函数选项。

【问题讨论】:

  • 这似乎不可能,正如错误所说。尝试Fn(T) 并没有让我有所收获。

标签: generics rust function-pointers traits type-alias


【解决方案1】:

目前看来不可能,也没有解决办法。

【讨论】:

    【解决方案2】:

    对于从 Rust 1.47.0 起仍然对此感到好奇的任何人,这仍然是不可能的,但看起来你会收到一条不错的小警告消息,其中包含描述和建议的替代方案。 例如

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

    产量

    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>;
    |
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      相关资源
      最近更新 更多