Reputation: 16705
How can I pass a reference to Arc<A>
so that the following code compiles successfully?
use std::sync::Arc;
trait A {
fn send(&self);
}
struct B;
impl A for B {
fn send(&self) {
println!("SENT");
}
}
fn ss(a: &Arc<A>) {
let aa = a.clone();
aa.send();
}
fn main() {
let a = Arc::new(B);
ss(&a);
}
If I omit the reference, it compiles okay, but Clippy warns me that in such situation in makes no sense.
Clippy error on the code without reference:
Compiling playground v0.0.1 (file:///playground)
warning: this argument is passed by value, but not consumed in the function body
--> src/main.rs:13:10
|
13 | fn ss(a: Arc<A>) {
| ^^^^^^ help: consider taking a reference instead: `&Arc<A>`
|
= note: #[warn(needless_pass_by_value)] on by default
= help: for further information visit https://rust-lang-nursery.github.io/rust-clippy/v0.0.186/index.html#needless_pass_by_value
Upvotes: 1
Views: 3992
Reputation: 59005
Well, the simplest fix is to just ignore Clippy. Many of the lints in Clippy aren't in the base compiler specifically because they can be wrong or inapplicable. Besides which, an Arc
is already a kind of reference, and taking an &Arc<_>
(or &Rc<_>
) rarely makes much sense.
Secondly, as red75prime noted, you can change the function to take &A
instead.
Finally, if you really want to appease Clippy, you could just do what it says:
fn main() {
let a = Arc::new(B);
{ let a: Arc<A> = a.clone(); ss(&a); }
}
The reason you have to do it this way is that you can only coerce the "outermost" layer of indirection. The let
coerces the Arc<B>
into an Arc<A>
, then creates a pointer to it.
If there's some reason ss
needs its argument to be an Arc
(such as cloning it), just ignore Clippy or disable that lint. If there's no reason ss
needs its argument to be an Arc
(you just need what's inside it), change ss
to take &A
instead.
That last one is mostly just for completeness.
Upvotes: 5
Reputation: 3861
You can pass a reference to an Arc
's content instead.
fn ss(a: &A) {
a.send();
}
fn main() {
let a = Arc::new(B);
ss(&*a);
}
Upvotes: 6