简体   繁体   English

什么&符号在Rust类型中意味着什么?

[英]What does the ampersand mean in a Rust type?

I've seen this code in the Rust documentation: 我在Rust文档中看到过这段代码:

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

what does the & in &self mean? 什么是& in &self意味着什么?

This means you'll be passing in a reference to the object, as opposed to moving the object itself. 这意味着您将传入对象的引用 ,而不是移动对象本身。 It's import 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. 因为当你没有指定& ,rust会将值移动到函数中,并且原始绑定不再具有所有权。 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 . 现在切换something 之前,被称为eat Because something only takes a reference , g still has ownership and you can continue on. 因为something只需要参考g仍然拥有所有权,你可以继续。 eat on the other hand moves g and you no longer can use g . eat另一方面移动g ,你不再可以使用g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM