Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between `mut a: &T` and `a: &mut T`? [duplicate]

Could someone explain what is the difference between these two and when is mut a: &T most often used?

like image 405
Daniel Fath Avatar asked Apr 16 '15 10:04

Daniel Fath


People also ask

What is the meaning of Mut ah?

mutʿah, (Arabic: “pleasure”) in Islamic law, a temporary marriage that is contracted for a limited or fixed period and involves the payment of money to the female partner.

What is the difference between nikah and Mutah?

(7) In 'Nikah' marriage, the wife has the right to get full dower whereas her counterpart in the 'mutta' marriage is authorized only to get a specified dower.

Who can do Mutah?

According to Twelver Shia jurisprudence, preconditions for mut'ah are: The bride must not be married, she must attain the permission of her wali if she has never been married before, she must be Muslim or belong to Ahl al-Kitab (People of the Book), she should be chaste, must not be a known adulterer, and she can only ...

Is Mutah allowed?

The mut'ah is practised by Shia Muslims while Sunni Muslims generally consider it haram - forbidden.


1 Answers

Function parameters and let bindings in Rust are proper patterns, like those at the left of => in match (except that let and parameter patterns must be irrefutable, that is, they must always match). mut a is just a part of pattern syntax and it means that a is a mutable binding. &mut T/&T, on the other hand, is a type - mutable or immutable reference.

There are four possible combinations of mut in references and patterns:

    a: &T      // immutable binding of immutable reference
mut a: &T      // mutable binding of immutable reference
    a: &mut T  // immutable binding of mutable reference
mut a: &mut T  // mutable binding of mutable reference

The first variant is absolutely immutable (without taking internal mutability of Cell and such into account) - you can neither change what a points to nor the object it currently references.

The second variant allows you to change a to point somewhere else but it doesn't allow you to change the object it points to.

The third variant does not allow to change a to point to something else but it allows mutating the value it references.

And the last variant allows both changing a to reference something else and mutating the value this reference is currently pointing at.

Taking the above into account you can see where mut a: &T can be used. For example, you can write a search of a part of a string in a loop for the further usage like this:

let mut s: &str = source;
loop {
    // ... whatever
    s = &source[i..j];
}
// use the found s here
like image 200
Vladimir Matveev Avatar answered Oct 13 '22 20:10

Vladimir Matveev