采用 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 justself
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 guessself
also works?
如您所见,这正是 &self
的情况。如果您使用 self
(或 &mut self
),该方法可能仍会编译,但它只能在更受限制的情况下使用。
关于rust - 什么时候在方法中使用 self、&self 和 &mut self?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59018413/