gpt4 book ai didi

struct - 使用结构存储对非复制值的引用

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

我需要一个包含对进程子进程的引用并使我能够在其上执行函数的对象。

pub struct Shell {
child: std::process::Child,
}

impl Shell {
pub fn init() -> Shell {
let mut cmd = std::process::Command::new("Command");
let process = cmd.spawn();
let new = Shell {
child: process.unwrap(),
};
new
}

pub fn f1(mut self) {
//do something with self
}

pub fn f2(mut self) {
{
let stdin = self.child.stdin.as_mut().unwrap();
}
let output = self.child.wait_with_output();
}
}

fn main() {
let mut shell = Shell::init();
shell.f1();
shell.f2();
}
error[E0382]: use of moved value: `shell`
--> src/main.rs:28:5
|
27 | shell.f1();
| ----- value moved here
28 | shell.f2();
| ^^^^^ value used here after move
|
= note: move occurs because `shell` has type `Shell`, which does not implement the `Copy` trait

>Try it

问题是当我初始化我的对象时,我只能调用对象上的函数一次,因为由于标准的 Rust 行为,值在第一次调用时被移动。

一个简单的 #[derive(Copy, Clone)] 在这里不起作用,因为 std::process::Child似乎没有实现 Copy 特性。有没有办法规避它或将其包装成可复制的东西?

测试实现

当使用可变引用作为函数参数时,最初的问题似乎已解决,但是,无法多​​次访问 self.child

pub struct Shell {
child: std::process::Child,
}

impl Shell {
pub fn init() -> Shell {
let mut cmd = std::process::Command::new("Command");
let process = cmd.spawn();
let new = Shell {
child: process.unwrap(),
};
new
}

pub fn f1(&mut self) {
//do something with self
}

pub fn f2(&mut self) {
{
let stdin = self.child.stdin.as_mut().unwrap();
}
let output = self.child.wait_with_output();
}
}

fn main() {
let mut shell = Shell::init();
shell.f1();
shell.f2();
}
error[E0507]: cannot move out of borrowed content
--> src/main.rs:21:22
|
21 | let output = self.child.wait_with_output();
| ^^^^ cannot move out of borrowed content

>Try it

有办法解决吗?

最佳答案

问题是 self.child 必须被 wait_with_output() 消耗。这就是为什么 self 不能通过引用传递给 f2,而是通过值:

pub struct Shell {
child: std::process::Child,
}

impl Shell {
pub fn init() -> Shell {
let mut cmd = std::process::Command::new("Command");
let process = cmd.spawn();
let new = Shell {
child: process.unwrap(),
};
new
}

pub fn f1(&mut self) {
//do something with self
}

pub fn f2(mut self) {
{
let stdin = self.child.stdin.as_mut().unwrap();
}
let output = self.child.wait_with_output();
}
}

fn main() {
let mut shell = Shell::init();
shell.f1();
shell.f2();
}

>Try it

然而,这意味着 f2 必须是访问 self.child 的最后一个函数。

关于struct - 使用结构存储对非复制值的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52718513/

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