Reputation: 5031
To create a variable in Rust you'd use:
let var_name = 10;
This would also be valid:
let var_name: i32 = 10;
Constant variables are created like this:
const VAR_NAME: i32 = 10;
But if you tried to create a constant variable like this:
const VAR_NAME = 10;
You'd get an error that looks like this:
error: expected `:`, found `=`
--> src/main.rs:5:11
|
4 | const VAR_NAME = 10;
| ^ expected `:`
Having come from languages like JavaScript, Python & PHP this is kind of confusing to me.
Why is it that I have to specify a type definition when using const
but not when I use let
?
Upvotes: 26
Views: 5451
Reputation: 26757
Currently, there is a rule "Constants must be explicitly typed." (for static
: "A static item is similar to a constant").
But, you are right: the compiler could infer it. There is an open discussion about that: #1349, TL;DR:
const
and static
variableconst FOO = 22
would infer to i32
so probably not the type one would expect. So we'd end up writing const FOO = 22usize
.const-fn
, the type should be inferredIt may be worth mentioning that one of the guiding principle of type inference in Rust is that type inference should be local. This is the reason why, unlike in Haskell, function signatures always need to be fully specified. There are multiple reasons for this, notably it means easier reasoning for human readers and better error messages. This puts module level
const
in a tough spot, inference-wise. Matthieu M.
So far, there is still not a proposed RFC, so this issue stays open.
See also:
Upvotes: 32