rust - 什么时候在方法中使用 self、&self 和 &mut self?

标签 rust

采用 self 的方法与采用 &self 甚至 &mut self 的方法有什么区别?

例如

impl SomeStruct {
    fn example1(self) { }
    fn example2(&self) { }
    fn example3(&mut self) { }
}

假设我想实现一个将结构漂亮地打印到标准输出的方法,我应该采用 &self 吗?我想 self 也可以吗?我不确定什么时候使用什么。

最佳答案

来自示例in the book (只是分成三个单独的段落并标记可能使它更清楚):

&self: We’ve chosen &self here for the same reason we used &Rectangle in the function version: we don’t want to take ownership, and we just want to read the data in the struct, not write to it.

&mut self: If we wanted to change the instance that we’ve called the method on as part of what the method does, we’d use &mut self as the first parameter.

self: Having a method that takes ownership of the instance by using just self as the first parameter is rare; this technique is usually used when the method transforms self into something else and you want to prevent the caller from using the original instance after the transformation.

或者换句话说:区别与SomeStruct&SomeStruct&mut SomeStruct完全相同。

Say I want to implement a method that pretty prints the struct to stdout, should I take &self? I guess self also works?

如您所见,这正是 &self 的情况。如果您使用 self(或 &mut self),该方法可能仍会编译,但它只能在更受限制的情况下使用。

关于rust - 什么时候在方法中使用 self、&self 和 &mut self?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59018413/

相关文章:

rust - 如何将 PoisonError 包含在我自己的错误类型中

rust - 特性未实现(实现特性的事物)

rust - Borrow in filter closure 的生命周期不够长

rust - 为什么东京::选择!选择频率较高的 Action ?

rust - 如何使用字节数组键制作 BTreeMap?

rust - 使用 C/Fortran 库时 Rust ffi 中 undefined symbol 的问题

rust - 如何在不重复方法的情况下为结构实现多个特征?

iterator - 将结构的迭代器传递给接受 Rust 中引用的函数?

methods - 如何为此Rust特征使用相同的默认实现

rust - 将单个整数向量转换为单个二进制值向量