4 ms·
A similar macro the stdlib should have is poor_mans_cast!(foo as Bar::Qux) which expands to match foo { Bar::Qux(x) => Some(x), _ => None }.unwrap() which is a
by sdegutis 7y ago
A similar macro the stdlib should have is poor_mans_cast!(foo as Bar::Qux) which expands to match foo { Bar::Qux(x) => Some(x), _ => None }.unwrap() which is a questionably-hacky way to cast to a specific enum variant. I've had to use it twice because I couldn't figure out a more Rust-like way to solve the problem at hand.
- steveklabnik 7y agoCould you maybe whip up an example on https://play.rust-lang.org/ https://play.rust-lang.org/ ? It's not 100% clear to me what you're doing here, but I'm interested!
- sdegutis 7y agoThink for example of implementing a list interpreter. In certain situations, you know for a fact that an AST node is a given type. So you just want to cast from Node to Node::Symbol(s) to extract that std::string::String out of it. RFC #2593 seems like it would help here, and is something I've wanted for similar but unrelated reasons. So in the meantime I made poor_mans_cast!() macro to do this, which I've used twice already.
- bombela 7y agoDid you look at the if let syntax? if let Bar::Qux(x) = foo { ... )
- _-___________-_ 7y agoIt looks like they want to panic if the variant is not what they expect. Basically implement their own unwrap() for their own enum, since the above logic is basically what Option::unwrap() does for Option::Some. Assuming there's not some wider design issue, I'd probably implement an unwrap_qux() method on the Bar enum
- dodobirdlord 7y agoI look forward longingly to the day when RFC #2593 comes to pass. https://github.com/rust-lang/rfcs/pull/2593 https://github.com/rust-lang/rfcs/pull/2593