类似结构的枚举可以用作类型吗?
Can struct-like enums be used as types?
考虑以下(非法)示例:
enum Foo {
Bar { i: i32 },
Baz,
}
struct MyStruct {
field: Foo::Bar,
}
Foo::Bar
是一个 struct-like variant。我发现它们非常有用。但是,我有一个实例,我需要将结构的实例存储在另一个结构中,如上面 MyStruct
的示例。将 MyStruct::field
更改为 Foo
将是无效的,因为将字段更改为 Foo::Baz
没有意义。它只是 Foo::Bar
.
的一个实例
rustc
告诉我上面的代码无效:
error: found value name used as a type: DefVariant(DefId { krate: 0u32, node: 4u32 }, DefId { krate: 0u32, node: 5u32 }, true)
我只是做错了什么,还是这不可能?如果做不到,有没有什么打算?
我知道我可以像这样解决它,但我认为这是一个次等的选择,我希望尽可能避免它:
struct Bar {
i: i32,
}
enum Foo {
Bar(Bar),
Baz,
}
struct MyStruct {
field: Bar,
}
在第一种情况下,
enum Foo {
Bar { i: i32 },
Baz,
}
正如编译器告诉您的那样,Bar
不是类型而是值,不能用作类型 (error: found value name used as a type
)。
你的第二个构造是通常使用的,例如在标准库中 std::net::IpAddr
and std::net::SocketAddr
。
不,枚举变体本身不是类型,不能用作类型。
考虑以下(非法)示例:
enum Foo {
Bar { i: i32 },
Baz,
}
struct MyStruct {
field: Foo::Bar,
}
Foo::Bar
是一个 struct-like variant。我发现它们非常有用。但是,我有一个实例,我需要将结构的实例存储在另一个结构中,如上面 MyStruct
的示例。将 MyStruct::field
更改为 Foo
将是无效的,因为将字段更改为 Foo::Baz
没有意义。它只是 Foo::Bar
.
rustc
告诉我上面的代码无效:
error: found value name used as a type: DefVariant(DefId { krate: 0u32, node: 4u32 }, DefId { krate: 0u32, node: 5u32 }, true)
我只是做错了什么,还是这不可能?如果做不到,有没有什么打算?
我知道我可以像这样解决它,但我认为这是一个次等的选择,我希望尽可能避免它:
struct Bar {
i: i32,
}
enum Foo {
Bar(Bar),
Baz,
}
struct MyStruct {
field: Bar,
}
在第一种情况下,
enum Foo {
Bar { i: i32 },
Baz,
}
正如编译器告诉您的那样,Bar
不是类型而是值,不能用作类型 (error: found value name used as a type
)。
你的第二个构造是通常使用的,例如在标准库中 std::net::IpAddr
and std::net::SocketAddr
。
不,枚举变体本身不是类型,不能用作类型。