英文:
Destructure rust enum without matching
问题
以下是代码的翻译部分:
impl<'a> Debug for AstNode<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AstNode::Literal(inner) => inner.fmt(f),
AstNode::Variable(inner) => inner.fmt(f),
AstNode::Binary(inner) => inner.fmt(f),
AstNode::Unary(inner) => inner.fmt(f),
AstNode::Call(inner) => inner.fmt(f),
AstNode::Function(inner) => inner.fmt(f),
AstNode::If(inner) => inner.fmt(f),
AstNode::While(inner) => inner.fmt(f),
AstNode::Begin(inner) => inner.fmt(f),
AstNode::Assign(inner) => inner.fmt(f),
AstNode::NewGlobal(inner) => inner.fmt(f),
AstNode::Error(inner) => inner.fmt(f),
AstNode::TestAssert(inner) => inner.fmt(f),
AstNode::TestExpect(inner) => inner.fmt(f),
}
}
}
如果您需要更多的帮助,请随时提出。
英文:
What would be the correct way to simplify this strange code? There is no variant of AstNode
that doesn't wrap around an inner structure.
impl<'a> Debug for AstNode<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AstNode::Literal(inner) => inner.fmt(f),
AstNode::Variable(inner) => inner.fmt(f),
AstNode::Binary(inner) => inner.fmt(f),
AstNode::Unary(inner) => inner.fmt(f),
AstNode::Call(inner) => inner.fmt(f),
AstNode::Function(inner) => inner.fmt(f),
AstNode::If(inner) => inner.fmt(f),
AstNode::While(inner) => inner.fmt(f),
AstNode::Begin(inner) => inner.fmt(f),
AstNode::Assign(inner) => inner.fmt(f),
AstNode::NewGlobal(inner) => inner.fmt(f),
AstNode::Error(inner) => inner.fmt(f),
AstNode::TestAssert(inner) => inner.fmt(f),
AstNode::TestExpect(inner) => inner.fmt(f),
}
}
}
答案1
得分: 1
如果inner
成员不依赖于枚举变体,那么无需将其放入枚举中。您可以将其提升,因此无需匹配它。大致如下:
struct AstNode(AstKind, InnerType);
enum AstKind {
Literal,
Variable,
...
}
然后,您可以编写:
impl<'a> Debug for AstNode<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.1.fmt(f)
}
}
这种类型系统明确声明了InnerType
和AstKind
是独立的。如果我理解正确的话。
英文:
If the inner
member is not dependent on enum variant there is no need to put it in enum. You can promote it up, so there will be no need to match it. Something along those lines:
struct AstNode(AstKind, InnerType);
enum AstKind {
Literal,
Variable,
...
}
then you can write:
impl<'a> Debug for AstNode<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.1.fmt(f)
}
}
This type system explicitly states that InnerType
and AstKind
is independent. Which is your case If I understand correctly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论