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
?
As a general rule, you should always declare variables with const, if you realize that the value of the variable needs to change, go back and change it to let. Use let when you know that the value of a variable will change. Use const for every other variable.
Constants are used when you want to assign a value that doesn't change. This is helpful because if you try to change this, you will receive an error. It is also great for readability of the code. A person who reads your code will now know that this particular value will never change.
var declarations are globally scoped or function scoped while let and const are block scoped. var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared. They are all hoisted to the top of their scope.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With