考虑以下(非法)示例:
enum Foo {
Bar { i: i32 },
Baz,
}
struct MyStruct {
field: Foo::Bar,
}
Run Code Online (Sandbox Code Playgroud)
Foo::Bar是一个类似结构的变体.我发现它们非常有用.但是,我有一个实例,我需要在另一个结构中存储结构的实例,如上面的示例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)
Run Code Online (Sandbox Code Playgroud)
我只是做错了什么,或者这是不可能的?如果不可能,有没有计划呢?
我知道我可以像这样解决它,但我认为它是一个劣等选项,如果可能的话,我想避免它:
struct Bar {
i: i32,
}
enum Foo {
Bar(Bar),
Baz,
}
struct MyStruct {
field: Bar,
}
Run Code Online (Sandbox Code Playgroud)
在这第一种情况下,
enum Foo {
Bar { i: i32 },
Baz,
}
Run Code Online (Sandbox Code Playgroud)
因为编译器告诉你Bar不是类型而是值,并且不能用作类型(error: found value name used as a type).
第二种结构是通常使用的,例如在带有std::net::IpAddr和的标准库中std::net::SocketAddr.