gpt4 book ai didi

rust - 如何传递具有特征的 Arc 作为引用?

转载 作者:行者123 更新时间:2023-11-29 08:22:00 24 4
gpt4 key购买 nike

如何传递对 Arc<A> 的引用以便以下代码编译成功?

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);
}

( playground )

如果我省略引用,它可以编译,但 Clippy 警告我在这种情况下 in 是没有意义的。

code without reference 上的 Clippy 错误:

  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

最佳答案

您可以改为传递对 Arc 内容的引用。

fn ss(a: &A) {
a.send();
}

fn main() {
let a = Arc::new(B);
ss(&*a);
}

关于rust - 如何传递具有特征的 Arc 作为引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48851650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com