Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  • Isn't it a step back to use let to declare a variable?:

    let hi = "hi";
    
  • Type inference and the assignment operator should be enough, or aren't they?:

    hi = "hi";
    

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.

  • What is the rationale behind forcing the users to write let? In particular, what is the rationale against making let optional?
like image 222
gnzlbg Avatar asked Jun 03 '13 08:06

gnzlbg


People also ask

What is needed to declare a variable?

Declaring (Creating) Variablestype variableName = value; Where type is one of Java's types (such as int or String ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

What is the difference between LET and variable?

var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped. Variable declared by let cannot be redeclared and must be declared before use whereas variables declared with var keyword are hoisted.

Should I be using VAR or let?

let is preferable to var because it reduces the scope in which an identifier is visible. It allows us to safely declare variables at the site of first use. const is preferable to let .

Is let a variable?

In JavaScript, let is a keyword that is used to declare a block scoped variable. Usually, the var keyword is used to declare a variable in JavaScript which is treated as a normal variable, but the variables declared using the let keyword are block scoped.


1 Answers

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();.

like image 51
Corey Richardson Avatar answered Oct 03 '22 23:10

Corey Richardson