当无法将 FnBox 闭包放入 Arc 时,如何克隆它?
How can I clone a FnBox closure when it cannot be put into an Arc?
我想向不同的线程发送命令(闭包),闭包捕获非 Sync
变量(因此我不能 "share" 带有 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
,并定义 FnOnce
或 Invoke
特征。
生锈 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 ...
}
另请参阅:
生锈 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();
}
您甚至可以将此逻辑提取到 "factory" 函数中。
让我们深入了解一下。首先,我们认识到 Box<FnBox>
是一个 特征对象 ,克隆它们有点困难。根据 中的答案,并使用较小的案例,我们最终得到:
#![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();
}
值得注意的是,我们必须引入一个特征来实现克隆,并引入另一个特征以将克隆特征与 FnBox
.
相结合
然后是 "just" 为 FnBox
的所有实现者实现 MyFnBox
并启用另一个夜间功能的问题:#![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 ...
}
我想向不同的线程发送命令(闭包),闭包捕获非 Sync
变量(因此我不能 "share" 带有 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
,并定义 FnOnce
或 Invoke
特征。
生锈 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 ...
}
另请参阅:
生锈 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();
}
您甚至可以将此逻辑提取到 "factory" 函数中。
让我们深入了解一下。首先,我们认识到 Box<FnBox>
是一个 特征对象 ,克隆它们有点困难。根据
#![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();
}
值得注意的是,我们必须引入一个特征来实现克隆,并引入另一个特征以将克隆特征与 FnBox
.
然后是 "just" 为 FnBox
的所有实现者实现 MyFnBox
并启用另一个夜间功能的问题:#![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 ...
}