Vector 如何从装箱特征对象的另一个向量生成装箱特征对象的向量?
我正在做一个机器人。当bot收到消息时,它需要检查所有命令是否触发消息,如果是,则执行操作 所以我在主结构中有一个命令向量(Vector 如何从装箱特征对象的另一个向量生成装箱特征对象的向量?,vector,rust,borrow-checker,Vector,Rust,Borrow Checker,我正在做一个机器人。当bot收到消息时,它需要检查所有命令是否触发消息,如果是,则执行操作 所以我在主结构中有一个命令向量(Commandtrait): struct Bot { cmds: Vec<Box<Command>>, } 错误: bot.rs:167:44: 167:56 error: mismatched types: expected `Box<Command>`, found `&Box<Command>
Command
trait):
struct Bot {
cmds: Vec<Box<Command>>,
}
错误:
bot.rs:167:44: 167:56 error: mismatched types:
expected `Box<Command>`,
found `&Box<Command>`
(expected box,
found &-ptr) [E0308]
但它给了我:
bot.rs:172:46: 172:50 error: cannot borrow `*self` as mutable because `self.cmds` is also borrowed as immutable [E0502]
bot.rs:172
c.fire(&message, self);
因此,我找到了它,并找到了上面的解决方案
我做错了什么?我试了很多,但都没用。最初,我做了以下工作:
for c in &self.cmds {
if c.check(&message) {
c.fire(&message, self);
}
}
for c in &self.cmds {
if c.check(&message) {
c.fire(&message, self);
}
}
如果fire
功能不需要访问其他命令,可以选择使用空向量临时替换self.cmd
:
trait Command {
fn check(&self, message: &str) -> bool;
fn fire(&mut self, bot: &Bot);
}
struct Bot {
cmds: Vec<Box<Command>>,
}
impl Bot {
fn test(&mut self, message: &str) {
use std::mem;
// replace self.cmds with a empty vector and returns the
// replaced vector
let mut cmds = mem::replace(&mut self.cmds, Vec::default());
for c in &mut cmds {
if c.check(message) {
c.fire(self);
}
}
// put back cmds in self.cmds
mem::replace(&mut self.cmds, cmds);
}
}
我做错了什么?我试了很多,但都没用。最初,我做了以下工作:
for c in &self.cmds {
if c.check(&message) {
c.fire(&message, self);
}
}
for c in &self.cmds {
if c.check(&message) {
c.fire(&message, self);
}
}
如果fire
功能不需要访问其他命令,可以选择使用空向量临时替换self.cmd
:
trait Command {
fn check(&self, message: &str) -> bool;
fn fire(&mut self, bot: &Bot);
}
struct Bot {
cmds: Vec<Box<Command>>,
}
impl Bot {
fn test(&mut self, message: &str) {
use std::mem;
// replace self.cmds with a empty vector and returns the
// replaced vector
let mut cmds = mem::replace(&mut self.cmds, Vec::default());
for c in &mut cmds {
if c.check(message) {
c.fire(self);
}
}
// put back cmds in self.cmds
mem::replace(&mut self.cmds, cmds);
}
}
请提供一个允许任何其他人重现您遇到的问题的列表。否则,我们必须进行大量猜测才能生成代码,否则我们可能会生成错误的代码。首先,您可能不应该生成Vec,因为向量将在堆上分配其所有元素,因此再次对其进行框选只会减慢元素的创建。请提供一个允许其他人重现您遇到的问题的框。否则,我们必须进行大量猜测才能生成代码,否则我们可能会生成错误的东西。首先,您可能不应该生成Vec,因为向量将在堆上分配其所有元素,因此再次对其进行框选只会减慢元素创建。OP声明
命令
是一种特性,而不是结构。这就是为什么我想要一个MCVE。。。然而,你的下半场可能是正确的解决方案。您应该解释为什么在迭代self.messages
时传递self
是无效的-如何fire
尝试修改messages
。或者,OP可以分解self
,只将一部分字段传递给fire
@Shepmaster,因为它提醒我命令是一种特性。我习惯于看到一个问题不能提供MCVE。。。如果fire
接收到&Bot
,则“howfire
可能尝试修改消息”的情况不会发生,我认为编译器在这里是死板的。OP声明命令
是一种特性,而不是结构。这就是为什么我想要一个MCVE。。。然而,你的下半场可能是正确的解决方案。您应该解释为什么在迭代self.messages
时传递self
是无效的-如何fire
尝试修改messages
。或者,OP可以分解self
,只将一部分字段传递给fire
@Shepmaster,因为它提醒我命令是一种特性。我习惯于看到一个问题不能提供MCVE。。。如果fire
接收到&Bot
,那么“howfire
可能试图修改消息”的情况就不会发生,我认为编译器在这里过于严格。