Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

rust - Can struct-like enums be used as types?

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,
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...