Rust必须在此上下文中知道此值的类型

时间:2017-10-06 08:10:46

标签: rust

我在修复Rust中的以下错误时遇到问题:

error[E0619]: the type of this value must be known in this context
  --> src\factory\mod.rs:35:7
   |
35 |       bot.add_new_instruction(transfer_instruction);
   |       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

工厂/ mod.rs

mod bot;
use self::bot::*;

pub struct Factory {
    bots: Vec<Bot>,
}

impl Factory {
    pub fn new() -> Factory {
        Factory { bots: Vec::new() }
    }

    pub fn interpret_instruction(&mut self) {
        let low_chip_transfer_target = ChipTransferTarget::Bot(5);
        let high_chip_transfer_target = ChipTransferTarget::Bot(1);
        let from_bot = 2;

        let transfer_instruction =
            ChipTransferInstruction::new(low_chip_transfer_target, high_chip_transfer_target);
        let bot = self.bots[from_bot];

        // Erroneous line below
        bot.add_new_instruction(transfer_instruction);
    }
}

工厂/ bot.rs

#[derive(Debug)]
pub enum ChipTransferTarget {
    Output(usize),
    Bot(usize),
}

#[derive(Debug)]
pub struct ChipTransferInstruction {
    pub low_value_target: ChipTransferTarget,
    pub high_value_target: ChipTransferTarget,
}

impl ChipTransferInstruction {
    pub fn new(
        low_value_target: ChipTransferTarget,
        high_value_target: ChipTransferTarget,
    ) -> ChipTransferInstruction {
        ChipTransferInstruction {
            low_value_target,
            high_value_target,
        }
    }
}

pub struct Bot {
    id: usize,
    transfer_instructions: Vec<ChipTransferInstruction>,
}

impl Bot {
    pub fn new(id: usize) -> Bot {
        Bot {
            id,
            transfer_instructions: Vec::new(),
        }
    }

    pub fn add_new_instruction(&mut self, instruction: ChipTransferInstruction) {
        self.transfer_instructions.push(instruction);
    }
}

我删除了与此错误无关的代码,因为有更多逻辑。

我已尝试在bot方法中对transfer_instructioninterpret_instruction进行注释,但我仍然遇到同样的错误,而且我不确定这是错误的。

我已经研究过这个错误信息,大多数问题都是关于没有注释的向量和流,但是我可以告诉编译器能够在这里推断出每个变量的类型。

1 个答案:

答案 0 :(得分:1)

由于user4815162342的评论,我设法解决了这个问题。

我删除了太多。在我以前的代码中:

for capture in move_chips_regex.captures_iter(input) {
    let from_bot = capture[1].parse().unwrap();

其中move_chips_regex是正则表达式。

此修复程序将from_bot注释为usize,如下所示:

let from_bot: usize = capture[1].parse().unwrap();