gpt4 book ai didi

rust - 当无法将 FnBox 闭包放入 Arc 时,如何克隆它?

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

我想向不同的线程发送命令(闭包),闭包捕获一个非Sync变量(因此我不能与Arc“共享”闭包>,如 Can you clone a closure? 中所述。

闭包只捕获实现Clone的元素,所以我觉得闭包也可以派生Clone

#![feature(fnbox)]

use std::boxed::FnBox;
use std::sync::mpsc::{self, Sender};
use std::thread;

type Command = Box<FnBox(&mut SenderWrapper) + Send>;

struct SenderWrapper {
tx: Option<Sender<u64>>,
}
impl SenderWrapper {
fn new() -> SenderWrapper {
SenderWrapper { tx: None }
}
}

fn main() {
let (responses_tx, responses_rx) = mpsc::channel();
let closure: Command = Box::new(move |snd: &mut SenderWrapper| {
snd.tx = Some(responses_tx); // Captures tx, which is not Sync but is Clone
});

let mut commands = Vec::new();
for i in 0..2i32 {
let (commands_tx, commands_rx) = mpsc::channel();
commands.push(commands_tx);
thread::spawn(move || {
let mut wrapper = SenderWrapper::new();
let command: Command = commands_rx.recv().unwrap();
command.call_box((&mut wrapper,));
// Continue ...
});
}

for tx in commands.iter() {
commands[0].send(closure.clone()).unwrap(); // How can I make this clone() work?
}
// use answers ...
}
error[E0599]: no method named `clone` found for type `std::boxed::Box<for<'r> std::boxed::FnBox<(&'r mut SenderWrapper,), Output=()> + 'static>` in the current scope
--> src/main.rs:40:34
|
40 | commands[0].send(closure.clone()).unwrap();
| ^^^^^
|
= note: the method `clone` exists but the following trait bounds were not satisfied:
`std::boxed::Box<for<'r> std::boxed::FnBox<(&'r mut SenderWrapper,), Output=()>> : std::clone::Clone`

在当前语法中有什么方法可以实现/派生闭包的特征吗?

一个肮脏的解决方法是(手动)定义一个包含所需环境的结构,实现Clone,并定义FnOnceInvoke 特质。

最佳答案

使用rust 1.35

Box<dyn FnOnce>稳定。如果您将代码更改为仅在克隆后封闭闭包,您的代码现在可以在稳定的 Rust 中运行:

use std::sync::mpsc::{self, Sender};
use std::thread;

type Command = Box<FnOnce(&mut SenderWrapper) + Send>;

struct SenderWrapper {
tx: Option<Sender<u64>>,
}
impl SenderWrapper {
fn new() -> SenderWrapper {
SenderWrapper { tx: None }
}
}

fn main() {
let (responses_tx, responses_rx) = mpsc::channel();
let closure = move |snd: &mut SenderWrapper| {
snd.tx = Some(responses_tx); // Captures tx, which is not Sync but is Clone
};

let mut commands = Vec::new();
for i in 0..2i32 {
let (commands_tx, commands_rx) = mpsc::channel();
commands.push(commands_tx);
thread::spawn(move || {
let mut wrapper = SenderWrapper::new();
let command: Command = commands_rx.recv().unwrap();
command(&mut wrapper);
// Continue ...
});
}

for tx in commands.iter() {
tx.send(Box::new(closure.clone())).unwrap(); // How can I make this clone() work?
}
// use answers ...
}

另见:

使用rust 1.26

闭包现在实现 Clone

之前

这并没有回答您的直接问题,但是在将变量捕获到闭包之前克隆它们是否可行?

for tx in commands.iter() {
let my_resp_tx = responses_tx.clone();
let closure = Box::new(move |snd: &mut SenderWrapper| {
snd.tx = Some(my_resp_tx);
});
commands[0].send(closure).unwrap();
}

您甚至可以将此逻辑提取到“工厂”函数中。


让我们深入了解一下。首先,我们认识到 Box<FnBox>是一个特征对象,克隆它们有点困难。按照 How to clone a struct storing a boxed trait object? 中的答案,并使用更小的情况,我们最终得到:

#![feature(fnbox)]

use std::boxed::FnBox;

type Command = Box<MyFnBox<Output = ()> + Send>;

trait MyFnBox: FnBox(&mut u8) + CloneMyFnBox {}

trait CloneMyFnBox {
fn clone_boxed_trait_object(&self) -> Box<MyFnBox<Output = ()> + Send>;
}

impl<T> CloneMyFnBox for T
where
T: 'static + MyFnBox + Clone + Send,
{
fn clone_boxed_trait_object(&self) -> Box<MyFnBox<Output = ()> + Send> {
Box::new(self.clone())
}
}

impl Clone for Box<MyFnBox<Output = ()> + Send> {
fn clone(&self) -> Box<MyFnBox<Output = ()> + Send> {
self.clone_boxed_trait_object()
}
}

fn create() -> Command {
unimplemented!()
}

fn main() {
let c = create();
c.clone();
}

值得注意的是,我们必须引入一个 trait 来实现克隆,并引入另一个 trait 来将克隆 trait 与 FnBox 结合起来。 .

那么这“只是”一个实现问题 MyFnBox对于 FnBox 的所有实现者并启用另一个夜间功能:#![clone_closures] (定于 stabilization in Rust 1.28 ):

#![feature(fnbox)]
#![feature(clone_closures)]

use std::boxed::FnBox;
use std::sync::mpsc::{self, Sender};
use std::thread;

struct SenderWrapper {
tx: Option<Sender<u64>>,
}
impl SenderWrapper {
fn new() -> SenderWrapper {
SenderWrapper { tx: None }
}
}

type Command = Box<MyFnBox<Output = ()> + Send>;

trait MyFnBox: FnBox(&mut SenderWrapper) + CloneMyFnBox {}

impl<T> MyFnBox for T
where
T: 'static + FnBox(&mut SenderWrapper) + Clone + Send,
{
}

trait CloneMyFnBox {
fn clone_boxed_trait_object(&self) -> Box<MyFnBox<Output = ()> + Send>;
}

impl<T> CloneMyFnBox for T
where
T: 'static + MyFnBox + Clone + Send,
{
fn clone_boxed_trait_object(&self) -> Box<MyFnBox<Output = ()> + Send> {
Box::new(self.clone())
}
}

impl Clone for Box<MyFnBox<Output = ()> + Send> {
fn clone(&self) -> Box<MyFnBox<Output = ()> + Send> {
self.clone_boxed_trait_object()
}
}

fn main() {
let (responses_tx, responses_rx) = mpsc::channel();
let closure: Command = Box::new(move |snd: &mut SenderWrapper| {
snd.tx = Some(responses_tx);
});

let mut commands = Vec::new();
for i in 0..2i32 {
let (commands_tx, commands_rx) = mpsc::channel();
commands.push(commands_tx);
thread::spawn(move || {
let mut wrapper = SenderWrapper::new();
let command: Command = commands_rx.recv().unwrap();
command.call_box((&mut wrapper,));
// Continue ...
});
}

for tx in commands.iter() {
commands[0].send(closure.clone()).unwrap(); // How can I make this clone() work?
}
// use answers ...
}

关于rust - 当无法将 FnBox 闭包放入 Arc 时,如何克隆它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28011803/

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