gnzlbg
gnzlbg

Reputation: 7415

Why do I need to write let to declare a variable?

In Haskell I don't need to write anything to declare a variable. In C++ I need to write auto, which as far as I know works in an analogous way to rust's let.

I'm just asking because the first thing that caught my attention while skimming through Rust's tutorial were the let's everywhere. I felt like, I shouldn't be needing to type it! The compiler already knows that I'm declaring a variable! For declaring uninitialized variables, one could argue that it might be nice to declare them with a type. But again, it's optional, a matter of style. The compiler can deduce the type at first use, and don't compile if it's not used and hence can't deduce the type.

Upvotes: 6

Views: 9232

Answers (2)

ember arlynx
ember arlynx

Reputation: 3291

I am not so sure about grammar considerations (I think omitting it would be fine, grammar-wise, just more complex), but let and variable assignment are not the same thing in Rust. let is 1. pattern matching, 2. binding introducing. You can only do x = 3 if x is a mutable slot, but you can always do let x = 3, it introduces a new binding of a possibly different type and mutability. Removing let would make the current binding semantics impossible. It would also make patterns much more difficult, if not impossible. For example, let (a, b) = some_fn_returning_tuple();.

Upvotes: 3

snf
snf

Reputation: 3087

This is inferred from ML syntax and in ML you don't declare variables, you declare bindings to values.

So it's just a convention, but unless you declare it as mutable, you must think of it as a binding. I don't think that there is a reason to it, but just to make it better "parseable" and keep the language clean.

Upvotes: 1

Related Questions