Malekai
Malekai

Reputation: 5031

Why do I have to specify the type for "const" variables but not for "let" variables?

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

Answers (1)

Stargateur
Stargateur

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:

  • We could technically infer the type of const and static variable
  • We do not use them very often so it's not very annoying to annotate the types
  • We should maybe limit type inference for constants/statics to only literal value
  • This could make error messages less accurate
  • Maybe limit type inference for constants/statics to local scopes like function bodies
  • For integers, const FOO = 22 would infer to i32 so probably not the type one would expect. So we'd end up writing const FOO = 22usize.
  • When the variable is initialized with a const-fn, the type should be inferred
  • When the variable is initialized with another variable typed explicitly
  • For arrays, the explicit type is very redundant
  • For variables which are only exported, we can end up not being able to infer their types (so it would be a compile-time error "type needs to be specified")

It 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

Related Questions