gpt4 book ai didi

rust - 如何使用堆分配的数据创建常量枚举变体以用于模式匹配?

转载 作者:行者123 更新时间:2023-11-29 08:26:57 25 4
gpt4 key购买 nike

我有这个枚举:

enum Foo {
Bar,
Baz(String),

// And maybe some other variants
}

我发现自己经常对 Baz 的预定义字符串进行模式匹配。

match foo_instance {
Foo::Baz(ref x) => match x.as_str() {
"stuff" => ...,
"anotherstuff" => ...,
},
// Other match cases...
}

有时我只匹配一个案例,有时是 4-5 个 Foo::Baz 案例。在后一种情况下,双重 match 并没有给我带来太大的困扰,事实上分组在这一点上是有意义的。如果我只匹配 Foo::Baz 的一种情况,它感觉不对。我真正想要做的是:

const STUFF: Foo = Foo::Baz("stuff".to_string());
const ANOTHER_STUFF: Foo = Foo::Baz("anotherstuff".to_string());

match foo_instance {
&STUFF => ...,
&ANOTHER_STUFF => ...,
// Other match cases...
}

当然,由于 to_string() 调用,这将不起作用(而且我还需要派生 Eq 特征才能匹配 consts 这很奇怪。这对我来说也可能是个问题。)。有没有办法模仿这个?例如,使用宏,我可以做这样的事情吗:

const STUFF: Foo = magic!(Foo::Baz("stuff".to_string());
const ANOTHER_STUFF: Foo = magic!(Foo::Baz("anotherstuff".to_string()));

// Or any other thing that can mimic top level behavior,
// I may create these constants dynamically at program start, that would work too.

match foo_instance {
another_magic!(STUFF) => ...,
another_magic!(ANOTHER_STUFF) => ...,
// Other match cases...
}

一般来说,我希望能够拥有一些包含堆分配数据(在本例中为 String)的枚举常量变体,以便我可以在需要时重用它们匹配 大小写。处理此问题的最佳方法是什么?

最佳答案

在当前的 Rust 中,你不能用堆分配的数据创建常量,句号。

也许 将来有可能创建一个const FOO: String,但在此之前还有很多工作要做,需要做出很多决定。

using a macro

不是魔法。它们只允许您编写您已经可以编写但使用新语法的某些类型的代码。由于您无法创建这些常量,因此您也无法编写宏来创建它们。


I want to somehow extract all the left hand side of the match case to a constant or something like that. Match guards doesn't help me with that(Yes, it eliminates the need for double match, but its a last resort for me.

Also map()ing my enum is not going to work, because it's not a struct, I need to match in map too.

Creating a parallel type seems too weird.

I can create a const static &str and match against that with those solutions but that would raise another problem. These constants will only have strings and they lack the total meaning.

There is only one solution that does what I need along those solutions presented and I found that one too verbose.

I have a lot of enums like this and it will be hard to create parallel types for each of them and apart from that, the solution is just verbose.

对于可以使用您已经放弃的替代解决方案的其他读者,另请参阅:

如需进一步阅读,另请参阅:

关于rust - 如何使用堆分配的数据创建常量枚举变体以用于模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50901218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com