gpt4 book ai didi

rust - 我如何使用 Rust 中的匹配语句拥有的值?

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

我的意图是匹配文本文件中每一行的值。如果该值与字符串匹配,则应将相应的操作码推送到向量中。否则,我想将值本身添加到向量中。该值本身不能使用,因为它属于另一个范围。

如果我错了,请改正,但我无法复制或克隆 line 的值,因为它没有实现正确的特征。在 match 语句中借用值然后将其用作默认值 (_) 的最佳解决方案是什么,以防它不匹配任何字符串?

let buffered = BufReader::new(input);

for line in buffered.lines() {
match line.unwrap().as_ref() {
"nop" => instructions.push(0x00),
"push" => instructions.push(0x01),
"print" => instructions.push(0x02),
"add" => instructions.push(0x03),
"halt" => instructions.push(0xff),
_ => instructions.push(line.unwrap().as_bytes()[0]),
}
}

最佳答案

使用任意值代替 _。语句现在看起来像这样:

for line in buffered.lines() {
match line.unwrap().as_ref() {
"nop" => instructions.push(0x00),
"push" => instructions.push(0x01),
"print" => instructions.push(0x02),
"add" => instructions.push(0x03),
"halt" => instructions.push(0xff),
x => instructions.push(x.as_bytes()[0]),
}
}

关于rust - 我如何使用 Rust 中的匹配语句拥有的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53801429/

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