可以将类似struct的枚举用作类型吗? [英] Can struct-like enums be used as types?
问题描述
考虑以下(非法)示例:
枚举Foo {
Bar {i:i32},
Baz,
}
struct MyStruct {
栏位:Foo :: Bar,
}
Foo :: Bar
是类似结构的变体。我发现它们非常有用。但是,我有一个实例,需要在另一个结构中存储该结构的实例,例如上述 MyStruct
的示例。将 MyStruct :: field
更改为 Foo
将是无效的,因为对于该字段而言,这没有意义。是 Foo :: Baz
。
rustc code>告诉我上面的代码无效:
错误:找到的值名称用作类型:DefVariant(DefId {krate:0u32,node:4u32},DefId {krate:0u32,node:5u32},true)
我是在做错什么,还是不可能?如果不可能的话,有什么计划吗?
我知道我可以像这样解决它,但我认为这是一个次等选择,这是我的选择d尽可能避免:
struct Bar {
i:i32,
}
枚举Foo {
Bar(Bar),
Baz,
}
struct MyStruct {
栏位:Bar,
}
在第一种情况下,
枚举Foo {
Bar {i:i32},
Baz,
}
编译器告诉您 Bar
不是类型而是值,并且不能用作类型(错误:找到的值名称用作类型
)。
您第二次构造是通常使用的格式,例如在标准库中使用 std :: net :: IpAddr
和 std :: net :: SocketAddr
。
Consider the following (illegal) example:
enum Foo {
Bar { i: i32 },
Baz,
}
struct MyStruct {
field: Foo::Bar,
}
Foo::Bar
is a struct-like variant. I've found them to be quite useful. However, I have an instance where I need to store an instance of the struct inside another struct, like the above example of MyStruct
. Changing MyStruct::field
to be a Foo
would be invalid, as it doesn't make sense for the field to be a Foo::Baz
. It's just meant to be an instance of Foo::Bar
.
rustc
tells me the above code is invalid:
error: found value name used as a type: DefVariant(DefId { krate: 0u32, node: 4u32 }, DefId { krate: 0u32, node: 5u32 }, true)
Am I just doing something wrong, or is this not possible? If it's not possible, are there any plans on doing it?
I know I could work around it like this, but I consider it an inferior option and it's one I'd like to avoid if possible:
struct Bar {
i: i32,
}
enum Foo {
Bar(Bar),
Baz,
}
struct MyStruct {
field: Bar,
}
In this first situation,
enum Foo {
Bar { i: i32 },
Baz,
}
as the compiler tells you Bar
is not a type but a value, and cannot be used as a type (error: found value name used as a type
).
You second construction is what is generally used, for example in the standard library with std::net::IpAddr
and std::net::SocketAddr
.
这篇关于可以将类似struct的枚举用作类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!