Rust 防锈油接头的使用特点
我正在做我的大学作业。Rust 防锈油接头的使用特点,rust,Rust,我正在做我的大学作业。 任务是使用变量字段(union)对结构中的数据进行排序。 我们通常使用C,但我决定尝试生锈,并面临一个问题/ 我不明白如何修正我的错误。 union中的一个结构必须包含字符串。 据我所知,问题出在这个字符串中。 我的结构: pub struct Show { theatre: String, name: String, director: String, price_min: i64, price_max: i64, typ
任务是使用变量字段(union)对结构中的数据进行排序。
我们通常使用C,但我决定尝试生锈,并面临一个问题/ 我不明白如何修正我的错误。
union中的一个结构必须包含字符串。
据我所知,问题出在这个字符串中。
我的结构:
pub struct Show
{
theatre: String,
name: String,
director: String,
price_min: i64,
price_max: i64,
type_name: ShowType,
type_data: ShowTypeData,
}
enum ShowType
{
Childish,
Adultish,
Musical,
}
union ShowTypeData
{
childish: ChildishShow,
adultish: AdultishShow,
musical: MusicalShow,
}
struct ChildishShow
{
age_target: i8,
subtype: ChildishShowType,
}
enum ChildishShowType
{
Tale,
Piece,
}
struct AdultishShow
{
subtype: AdultishShowType,
}
enum AdultishShowType
{
Piece,
Dramma,
Comedy,
}
struct MusicalShow
{
composer: String,
country: String,
age_min: i8,
duration: i16,
}
错误:
error[E0658]: unions with non-`Copy` fields are unstable
--> src/show.rs:19:1
|
19 | / union ShowTypeData
20 | | {
21 | | childish: ChildishShow,
22 | | adultish: AdultishShow,
23 | | musical: MusicalShow,
24 | | }
| |_^
|
= note: see issue #55149 <https://github.com/rust-lang/rust/issues/55149> for more information
error[E0740]: unions may not contain fields that need dropping
--> src/show.rs:23:5
|
23 | musical: MusicalShow,
| ^^^^^^^^^^^^^^^^^^^^
|
note: `std::mem::ManuallyDrop` can be used to wrap the type
--> src/show.rs:23:5
|
23 | musical: MusicalShow,
| ^^^^^^^^^^^^^^^^^^^^
error[E0658]:具有非-Copy`字段的联合不稳定
-->src/show.rs:19:1
|
19 |/联合显示类型数据
20 | | {
21 | |孩子气的:孩子气的表演,
22 | | |成人化:成人秀,
23 | |音乐剧:音乐表演,
24 | | }
| |_^
|
=注:有关更多信息,请参阅问题#55149
错误[E0740]:联合可能不包含需要删除的字段
-->src/show.rs:23:5
|
23 |音乐剧:音乐表演,
| ^^^^^^^^^^^^^^^^^^^^
|
注意:`std::mem::ManuallyDrop`可用于包装类型
-->src/show.rs:23:5
|
23 |音乐剧:音乐表演,
| ^^^^^^^^^^^^^^^^^^^^
我不明白“复制”和“删除”的确切含义。这可能是我的问题。不要将联合从C复制到Rust逐字逐句 改为写:
pub struct Show
{
theatre: String,
name: String,
director: String,
price_min: i64,
price_max: i64,
show_type: ShowType,
}
enum ShowType
{
Childish(ChildishShow),
Adultish(AdultishShow),
Musical(MusicalShow),
}
工会是一种低水平的、本质上不安全的结构,在生锈的情况下,你可以投入的东西非常有限。尽可能使用
枚举
。没有接头,就没有问题。请构造一个合适的接头。给定的代码不完整,这使得我们很难重现所提出的确切问题。您可能需要重新考虑是否确实需要一个联合
,或者只需要一个枚举
。请注意,Rust中的enum
s实际上是求和类型,比C中的enum功能更强大。有关enum的更多信息,请参阅本书的第页。错误对我来说非常清楚。工会非常有限。你不确定“下降”是什么意思吗?你不确定“复制”是什么意思吗?我在“这是你的问题”之前学过Cunion
是一种非常低级且不安全的类型,仅存在于严格复制C联合的情况下,union
不应使用,除非您别无选择<代码>显示很可能是一个潜在可能性的枚举,但您没有提供真正有帮助的深度或广度信息。@БаааСаСааааСаааСаа。不,枚举不会一次为所有变量分配内存,但足以为最大的变量和变量鉴别器分配内存。内存效率如何?在C中,我必须使用union,因为它只为单个字段存储内存。锈蚀中的枚举是否相同?是的,相同,但更好。您的ShowType
将包含判别式和相应的数据。优点是您将无法访问错误的数据。