How can I use arbitrary text as a function name in Rust?

Viewed 765

Is there a way in Rust to use any text as a function name? Something like:

fn 'This is the name of the function'  { ... } 

I find it useful for test functions and it is is allowed by other languages.

2 Answers

There's no way. According to the official reference:

An identifier is any nonempty ASCII string of the following form:

Either

  • The first character is a letter.
  • The remaining characters are alphanumeric or _.

Or

  • The first character is _.
  • The identifier is more than one character. _ alone is not an identifier.
  • The remaining characters are alphanumeric or _.

A raw identifier is like a normal identifier, but prefixed by r#. (Note that the r# prefix is not included as part of the actual identifier.) Unlike a normal identifier, a raw identifier may be any strict or reserved keyword except the ones listed above for RAW_IDENTIFIER.

You can't have spaces in function names (and this is true of most programming languages). Usual practice for function names in Rust is to replace spaces with underscores, so the following is allowed:

fn This_is_the_name_of_the_function  { ... }

although usual practice would use a lower-case t

Related