Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the ampersand mean in a Rust type?

I've seen this code in the Rust documentation:

fn eat(&self) {     println!("{} is done eating.", self.name); } 

what does the & in &self mean?

like image 853
user3522940 Avatar asked Aug 09 '15 20:08

user3522940


People also ask

What is the * operator in Rust?

operator in Rust is used as an error propagation alternative to functions that return Result or Option types. The ? operator is a shortcut as it reduces the amount of code needed to immediately return Err or None from the types Result<T, Err> or Option in a function.

What does * do in Rust?

It dereferences num so you assign to the place in memory it points into (the num variable in main() ) and not to the num variable. The left-hand-side and right-hand-side of the assignment must be of the same type.

What does the asterisk do in Rust?

Explanation from the Rust site: You'll also notice we added an asterisk ( * ) in front of y , making it *y , this is because y is a &mut reference. You'll need to use astrisks [sic] to access the contents of a reference as well.

What is a closure in Rust?

Rust's closures are anonymous functions you can save in a variable or pass as arguments to other functions. You can create the closure in one place and then call the closure elsewhere to evaluate it in a different context. Unlike functions, closures can capture values from the scope in which they're defined.


1 Answers

This means you'll be passing in a reference to the object, as opposed to moving the object itself. It's important to distinguish this because if your function looked like:

fn eat(self) {     println!("{} is done eating.", self.name); } 

and you tried calling it then using the variable after, you'd get an error

object = Foo::new(); object.eat(); object.something(); // error, because you moved object in eat 

because when you don't specify &, rust moves the value into the function and your original binding no longer has ownership. check out this minimal example I created (playground version):

struct Foo {     x : u32 }  impl Foo {      fn eat(self) {         println!("eating");     }      fn something(&self) {         println!("else");     }  }  fn main() {     println!("Hello, world!");      let g = Foo { x: 5 };     g.eat();     g.something();  // if this comes before eat, no errors because we arent moving } 

Now switch something to be called before eat. Because something only takes a reference, g still has ownership and you can continue on. eat on the other hand moves g and you no longer can use g.

like image 199
Syntactic Fructose Avatar answered Oct 02 '22 03:10

Syntactic Fructose