Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Let &mut syntax

Tags:

syntax

rust

It is possible to make the following binding in Rust:

let &mut a = &mut 5;

But what does it mean exactly? For example, let a = &mut 5 creates an immutable binding of type &mut i32, let mut a = &mut 5 creates a mutable binding of type &mut i32. What about let &mut?

like image 932
Nikolai Mavrenkov Avatar asked Jul 08 '15 16:07

Nikolai Mavrenkov


People also ask

What is the use of LET?

We use let to talk about permission. Let is followed by an object and an infinitive without to: She let me look at the photos. Not: She let me to look … She'd live on pizzas if we let her.

What is the full meaning of let?

verb (used with object), let, let·ting. to allow or permit: to let him escape. to allow to pass, go, or come: to let us through. to grant the occupancy or use of (land, buildings, rooms, space, etc., or movable property) for rent or hire (sometimes followed by out).

How Use let in a sentence?

[M] [T] He let me stay for a night. [M] [T] Let's do this first of all. [M] [T] My parents let me go there. [M] [T] Now let's get down to work.

What is the similar meaning of let?

Some common synonyms of let are charter, hire, lease, and rent. While all these words mean "to engage or grant for use at a price," hire and let, strictly speaking, are complementary terms, hire implying the act of engaging or taking for use and let the granting of use.


1 Answers

An easy way to test the type of something is to assign it to the wrong type:

let _: () = a;

In this case the value is an "integral variable", or a by-value integer. It is not mutable (as testing with a += 1 shows).

This is because you are using destructuring syntax. You are pattern matching your &mut 5 against an &mut _, much like if you wrote

match &mut 5 { &mut a => {
// rest of code
} };

Thus you are adding a mutable reference and immediately dereferencing it.

To bind a mutable reference to a value instead, you can do

let ref mut a = 5;

This is useful in destructuring to take references to multiple inner values.

like image 76
Veedrac Avatar answered Jan 05 '23 00:01

Veedrac