Why Structs and Functions don't use 'let' keyword?

Normally, we're using 'let' keyword for variable declaration. But,

struct Person {
    name: str,
    age: i32,
}

and

fn Person(age: i32){

// do something
}

Does not use the 'let' keyword. Why ? Isn't that supposed to be done like this?

struct Person {
    **let** name: str,
    **let** age: i32,
}

and

fn Person(**let** age: i32){

// do something
}

I think it would be because let introduces a binding, where the struct definition is just creating the possibility for a binding. When you are defining a struct, there is no variable created. In order to create the name and age variables in a usable way, you then have to actually declare the Person variable, with

let p = Person { name : "name", age : 22 };

Which then declares the variables p.name and p.age.

This is the same with the function parameter; the variable is actually declared elsewhere, the parameter is just a placeholder.

My 2cents anyway.

2 Likes

The short answer is that it is simply not necessary.

2 Likes

I don't think there's any critical reason either use or not use the let keyword for it. Rust just decided to not use it in such case.

1 Like

Everything has a reason. I just wonder.

A lot of arbitrary syntax decisions in Rust exist merely because other languages did it this way, and Rust wants to have familiar-looking syntax. And other languages have their syntax also because of a mix of familiarity + arbitrary decisions + historical accidents.

4 Likes

Another reason is that requiring let in such circumstances would just add unnecessary clutter.

Having a way of differentiating binding declaration and variable affectation is useful. For example, it prevents code from compiling if you make a typo when assigning to an existing variable:

let mut foo = 42;
fob = 3; // typo here: won't compile

The syntactic way of doing this that was chosen by rust is let. Different languages choose different solutions, such as using different assignment and binding operators (e.g. = for assignment or := for binding), or requiring typing the type of a variable when introducing a binding (like in C, Java or C++ for instance).

In the case of a function or struct, giving names to variable already implicitly creates a binding, as no assignment to an existing binding is possible in this context. Hence, the let would not add more information. As a result, it is not used.

7 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.