为什么Clippy建议通过Arc作为参考? [英] Why does Clippy suggests passing an Arc as a reference?

查看:114
本文介绍了为什么Clippy建议通过Arc作为参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查代码中的Clippy发现,发现学究规则needless_pass_by_value 可能是误报.

I am checking Clippy findings in my code and found that the pedantic rule needless_pass_by_value might be a false positive.

它说:

警告:此参数按值传递,但不会在函数主体中使用

warning: this argument is passed by value, but not consumed in the function body

帮助:考虑参考:&Arc<Mutex<MyStruct>>

由于克隆Arc仅是参考计数,因此移动Arc应该不是一个坏主意.在质量和性能方面,发送参考而不是Arc的值真的有什么区别吗?

Since cloning the Arc is only reference counting, moving the Arc should not be bad idea. Does it really make any difference in terms of quality and performance to send a reference instead of a value for the 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);
    }
}

游乐场

推荐答案

调用arc_taker(arc.clone())会增加引用计数,而从arc_taker返回会再次减少引用计数.在这种情况下,这是没有用的,因为mainarc变量在整个调用过程中已经使Arc保持活动状态.引用它就足够了.无需增加引用计数.

Calling arc_taker(arc.clone()) increments the reference count, and returning from arc_taker decrements it again. This is useless in this case, since the arc variable of main already keeps the Arc alive during the entire call. A reference to it would already suffice. No need to bump the reference count up and down.

在您的特定示例中,arc_taker甚至都不关心它是由Arc管理的.它所关心的只是locklock,因此要使您的函数不受限制,只需改用&Mutex<MyStruct>.

In your specific example, arc_taker doesn't even care that it is managed by an 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.

如果您想对它进行任何Arc特定的操作,例如获取weak_count之类的东西,那么使用&Arc<..>将会很有意义.如果您的函数可以保留Arc的克隆,那么只有按值取一个Arc才有意义,因为调用者可以通过调用.clone()决定为您提供对其的附加引用(因此,参考计数),或为您提供其自己的Arc所有权(因此不会增加参考计数).

If you wanted to do any Arc-specific things to it, like getting the weak_count or something, taking a &Arc<..> would make sense. 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).

这篇关于为什么Clippy建议通过Arc作为参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆