Reputation: 2372
I have a file named 1_add.rs
, and I tried to add it into the lib.rs
. Yet, I got the following error during compilation.
error: expected identifier, found `1_add`
--> src/lib.rs:1:5
|
1 | mod 1_add;
| ^^^^^ expected identifier
It seems the identifier that starts with a digit is invalid. But why would Rust has this restriction? Is there any workaround if I want to indicate the sequence of different rust files (for managing the exercise files).
Upvotes: 3
Views: 2062
Reputation: 601679
Allowing identifiers to start with a digit would caus conflicts with many other token types. Here are a few examples:
1e1
is a floating point number.0x0
is a hexadecimal integer.8u8
is an integer with explicit type annotation.Most importantly, though, I believe allowing identifiers starting with digit would hurt readability. Currently everything starting with a digit is some kind of number, which in my opinion helps when reading code.
An incomplete list of programming languages not allowing identifiers to start with a digit: Python, Java, JavaScript, C#, Ruby, C, C++, Pascal. I can't think of a language that does allow this (which most likely does exist).
Upvotes: 3
Reputation: 38809
Rust identifiers are based on Unicode® Standard Annex #31
(see The Rust RFC Book), which standardizes some common rules for identifiers in programming languages. It might make it easier to parse text that could otherwise be ambiguous, like 1e10
?
Upvotes: 2
Reputation: 6984
In your case (you want to name the files like 1_foo.rs
) you can write
#[path="1_foo.rs"]
mod mod_1_foo;
Allowing identifies to start with digits can conflict with type annotations. E.g.
let foo = 1_u32;
sets to type to u32
. It would be confusing when 1_u256
means another variable.
Upvotes: 10
Reputation: 12600
"Why?" cannot be reasoned here but by historical tales, the rules are as such. You cannot play against them.
If you urgently want to start your identifiers with a digit, at least for human readers, prepend an underscore like this: _1_add
.
Note: To make sure that sorting works well, use also leading zeroes as many as appropriate (_001_add
if you expect more than 99 files).
Upvotes: 1
Reputation: 230346
But why would Rust has this restriction?
Not only rust, but most every language I've written a line of code in has this restriction as well.
Food for thought:
let a = 1_2;
Is 1_2
a variable name or is it a literal for value 12
? What if variable 1_2
does not exist now, but you add it later, does this token stop being a number literal?
While rust compiler probably could make it work, it's not worth all the confusion, IMHO.
Upvotes: 6