【问题标题】:Unable to type alias a specialised generic enum无法为专门的通用枚举键入别名
【发布时间】:2016-11-02 14:06:29
【问题描述】:

鉴于以下情况:

use std::fmt::Debug;

#[derive(Debug)]
enum A<T: Debug> {
    X,
    Y(T),
}

#[derive(Debug)]
struct B;

type C = A<B>;
// use A<B> as C; // Does not compile

我可以把它用作:

fn main() {
    let val0 = A::X::<B>;
    let val1 = A::Y::<B>(B);
    println!("{:?}\t{:?}", val0, val1);
}

但是对于不止一个通用参数(或者如果 AB 等名称更长,那么我尝试了以下操作但无法编译:

fn main() {
    let val0 = C::X;
    let val1 = C::Y(B);
    println!("{:?}\t{:?}", val0, val1);
}

有错误:

src/main.rs:656:16: 656:20 error: no associated item named `X` found for type `A<B>` in the current scope
src/main.rs:656     let val0 = C::X;
                               ^~~~
src/main.rs:657:16: 657:20 error: no associated item named `Y` found for type `A<B>` in the current scope
src/main.rs:657     let val1 = C::Y(B);

如前所述,我无法使用use 来解决问题。有没有办法绕过它(因为输入整个东西似乎很麻烦)?

rustc --version
rustc 1.9.0 (e4e8b6668 2016-05-18)

【问题讨论】:

  • 听起来好像缺少功能...

标签: enums rust


【解决方案1】:

有没有办法绕过它(因为输入整个东西似乎很麻烦)?

您可以将C 指定为变量的类型,这样您就可以使用A::XA::Y,而无需显式指定类型参数:

let val0: C = A::X;
let val1: C = A::Y(B);

【讨论】:

  • 哇!永远无法猜到——当C::X 失败时我放弃了。但是它以这种方式工作(而不是另一种方式)的事实似乎有点令人困惑,不是吗?尽管如此,它解决了我到处输入模板参数的问题,所以谢谢!
  • @ustulation 我相信 问题是A typeA namespace 是不同的据编译器所知的事情。 type 负责前者,而不是后者。情况不是很好,但它们是休息时间。我希望它会在一些点得到改进。
猜你喜欢
  • 2016-06-20
  • 2016-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多