PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, December 20, 2022

[FIXED] What does the ampersand (&) before `self` mean in Rust?

 December 20, 2022     rust, syntax, variables     No comments   

Issue

I've seen this code in the Rust documentation:

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

what does the & in &self mean?


Solution

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.



Answered By - Syntactic Fructose
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing