【发布时间】:2023-03-16 23:15:02
【问题描述】:
考虑这个解决Advent of Code 2015 1.2 的例子。
fn main() {
// advent of code 1.2 2015
// you are at floor 0
// if instruction is ) go one floor up, else go one floor down
// what index has the character that makes you go below floor 0
let instruction = ")))(((()))))";
let mut floor = 0;
for (i, c) in input.chars().enumerate() {
if c.to_string() == ")" {
floor += 1;
} else {
floor -= 1;
}
if floor < 0 {
break;
}
}
// will fail
println!("floor: {}", i)
}
如何在循环块之外访问i?
阅读了Understanding scope and shadowing matches 和this chapter of the book,我明白为什么我的代码失败了,但我不知道如何处理它并在块外使用i。 p>
我的问题是我没有理解 Rust 中作用域的用途吗?如果我想在循环范围之外使用它,是否应该将循环放在函数内部并返回i?
【问题讨论】:
-
卡尔,问一个单独的问题是可以的,但是把一个问题改写成另一个问题会很混乱。
-
@DietrichEpp 我明白这一点 - 但问题仍然是“使用循环块外枚举中的索引”。鉴于我得到的唯一答案,我理解我的示例让我看起来像是在寻找一种在字母表中查找
d索引的方法,而这只是一个示例。 -
好的,从上下文来看,我认为你是对的。我已恢复回滚。
标签: for-loop scope rust enumerate