Use of ampersand (&) in Rust


#1

Hi,

I am very new to Rust and I would like to know the difference between using the & character before the variable name and using it before the type name. I couldn’t find relevant info about this in the doc or anywhere else online.

For example what is the difference between:

fn test (&mut p: &mut i32) { … }

and

fn test (p: &mut i32) { … }

?

Is there any example anywhere explaining the usage and difference? Can p be used in both functions to reference an external integer and modify it? How?

Thanks


#2

The left hand side of the : is a pattern.

The second case is actually simpler:

fn test (p: &mut i32) { ... }

p is just a parameter of type &mut i32, i.e. a mutable reference to an integer.
You can modify it like this:

*p = 42;

The first case, the pattern is a destructuring pattern, i.e. it “undoes” the structure of the type:

fn test (&mut p: &mut i32) { ... }

in that case, p is just an i32. AFAIK it is not possible to modify the “external” integer with that one.
But at the call site, you still have to provide an argument of type &mut i32.
In fact that’s not really useful, you would rather just use a plain i32 parameter.

The following chapters in the rust book will provide more informations:
https://doc.rust-lang.org/stable/book/patterns.html
https://doc.rust-lang.org/stable/book/references-and-borrowing.html


#3

That’s what I thought too, that it isn’t really useful to use the pattern version but my actual concern is why is it then used before the implicit self argument in type methods? Any idea? I mean is the self argument in such methods a simple copy of the address of a type instance or what? Note that it still allows us to actually change the fields of the referenced instance, like in self.x = 5, provided we add mut after the & of course (i.e. &mut self). So I’m still confused about how this pattern/destructuring logic still applies with &self and &mut self.

Thanks


#4

The self parameter is not like that, it is not a pattern.


#5

If it’s not a pattern, what is it?

Anyone?


#6

It’s the self parameter. self means self: Self, &self means self: &Self, and &mut self means self: &mut Self. It’s just short-hand.


#7

Thanks.


#8

and self: Box<Self> means what it says (it’s the only way to write that, and its the fourth and currently final self parameter form).