4 ms·
I just installed rustc to test this example, turns out you cannot do pattern matching on function arguments like you can in erlang. note: `my_func` must be def
by dilatedmind 9y ago
I just installed rustc to test this example, turns out you cannot do pattern matching on function arguments like you can in erlang.
note: `my_func` must be defined only once in the value namespace of this module
- piinbinary 9y agoIt might be more accurate to call what Rust can do to function arguments "destructuring" rather than "pattern matching"
- steveklabnik 9y agoDestructuring is a feature of pattern matching, so yeah, this is slightly more specific. I don't think "pattern matching" is incorrect, though.
- myrrlyn 9y agoCorrect. One signature, one body. You can destructure args, but Erlang-style matching or overloading is not a thing. Which sometimes I miss
- zbentley 9y agoYou can get multiple dispatch using traits: http://smallcultfollowing.com/babysteps/blog/2014/09/30/multi-and-conditional-dispatch-in-traits/ http://smallcultfollowing.com/babysteps/blog/2014/09/30/mult... However, that's a fair amount of boilerplate for the feature, so I highly doubt it would pay off to use that pattern to e.g. convert Erlang code that makes heavy use of function-declaration pattern matching. Additionally, a lot of the true power of Erlang's dispatch-plus-pattern-matching is because of its runtime pattern matching (e.g. http://puredanger.github.io/tech.puredanger.com/2008/12/30/playing-with-erlang/ http://puredanger.github.io/tech.puredanger.com/2008/12/30/p...). You can't do that in function signatures in Rust; you can only match on things known at compile time. So if you were converting Erlang that made heavy use of this, you'd have to pull apart the compile-time-checkable (e.g. a function can be called with a string or a number) parts of function signatures, convert them into trait-based polymorphic dispatch locations, keep track of the runtime-checkable parts, and then convert them into 'match' statements or conditionals and make sure the right match code got run in the right trait-based dispatch locations. I suspect, past a pretty low number of functions making use of this, Rust code would either get very duplicated (if you have a separate trait method for each function name,argument-types tuple), or very tricky to deduplicate if you wanted to use the same trait methods for functions with the same argument-types signatures, but only run certain match code depending on the specific function/pattern that was called. That would work, but if you did it naively/formulaically, it would make for less-than-readable code, I think. TL;DR you can robotically implement the Erlang pattern in Rust if you want. You can hit a square peg really hard into a round hole and shave the corners off if you want, too.