[英]Why does Clippy suggests passing an Arc as a reference?
I am checking Clippy findings in my code and found that the pedantic rule needless_pass_by_value
might be a false positive. 我正在检查我的代码中的Clippy结果,发现迂腐规则needless_pass_by_value
可能是误报。
It says that: 它说:
warning: this argument is passed by value, but not consumed in the function body 警告:此参数按值传递,但未在函数体中使用
help: consider taking a reference instead:
&Arc<Mutex<MyStruct>>
帮助:考虑改为引用:&Arc<Mutex<MyStruct>>
Since cloning the Arc
is only reference counting, moving the Arc
should not be bad idea. 由于克隆Arc
只是引用计数,因此移动Arc
应该不是一个坏主意。 Does it really make any difference in terms of quality and performance to send a reference instead of a value for the Arc
? 发送参考而不是Arc
的值,在质量和性能方面是否真的有所不同?
#![warn(clippy::pedantic)]
use std::sync::{Arc, Mutex};
fn main() {
let my_struct = MyStruct { value: 3 };
let arc = Arc::new(Mutex::new(my_struct));
arc_taker(arc.clone());
}
fn arc_taker(prm: Arc<Mutex<MyStruct>>) {
prm.lock().unwrap().do_something();
}
struct MyStruct {
value: i32,
}
impl MyStruct {
fn do_something(&self) {
println!("self.value: {}", self.value);
}
}
Calling arc_taker(arc.clone())
increments the reference count, and returning from arc_taker
decrements it again. 调用arc_taker(arc.clone())
增加引用计数,并且从arc_taker
返回会再次减少它。 This is useless in this case, since the arc
variable of main
already keeps the Arc
alive during the entire call. 在这种情况下,这是无用的,因为main
的arc
变量已经在整个调用期间使Arc
保持活动状态。 A reference to it would already suffice. 对它的引用已经足够了。 No need to bump the reference count up and down. 无需上下颠倒引用计数。
In your specific example, arc_taker
doesn't even care that it is managed by an Arc
. 在您的具体示例中, arc_taker
甚至不关心它是由Arc
管理的。 All it cares about is that there is a Mutex
to lock
, so to make your function less restrictive, just take a &Mutex<MyStruct>
instead. 它所关心的只是有一个Mutex
可以lock
,所以为了减少你的功能限制,只需要使用&Mutex<MyStruct>
。
If you wanted to do any Arc
-specific things to it, like getting the weak_count
or something, taking a &Arc<..>
would make sense. 如果你想对它做任何特定于Arc
事情,比如获取weak_count
或其他东西,那么取一个&Arc<..>
会有意义。 If your function would keep a clone of the Arc around, only then it would make sense to take an Arc
by value, because then the caller can decide to give you an additional reference to it by calling .clone()
(thus bumping the reference count), or to give you ownership of its own Arc
(and thus not bumping the reference count). 如果你的函数会保留Arc的克隆,那么只有这样才能获得一个Arc
by值,因为然后调用者可以通过调用.clone()
来决定给你一个额外的引用(从而撞击引用) count),或者给你自己的Arc
所有权(因此不会碰到引用计数)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.