Rust Syntax: When is it appropriate to use "=>"

When would a rust programmer use to following fat arrow operator => .

a) Is it only for match and macros?

b) Why is the lexeme on the left operand as apposed to being on the right operand?

';' => Semi,
',' => Comma,
'.' => Dot,
'(' => OpenParen,


Semi => ';'  ,
Comma => ','  ,

The above is scanning lexemes to validate a token which is then passed on to the next phase of the lexical analysis process.

Thank you kindly

=> is not an operator as such, it's part of the syntax of match and macro_rules!. The difference is there's no foo => bar meaning in isolation for the compiler, only when on the context of a match block, etc. (Technically this is true of all syntax, but the general assumption is that you're in a function body or the like)

You can read it in both those cases as meaning "when you match the pattern on the left, output the right": for match this is pattern matching a runtime value, for macro_rules! it's syntax. The direction is technically arbitrary, but the pattern is generally far smaller, and it's the established convention from other languages with similar features.


Awesome. Thank you kindly! Im going through Rust by example now. So a good bit of reading. Thanks for explaining that.

Both of these are valid match arms. The difference is in whether you want to convert from a char to a token enum, or from the enum to the char.

1 Like

Thank you kindly.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.