You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中如何在enumerate循环外部访问其返回的索引变量i?

解决Rust中enumerate索引在循环外部访问的问题

首先,你遇到的问题是变量作用域导致的:在Rust里,for循环中声明的i变量只存在于循环块的内部,当循环结束后,这个变量就超出了作用域,自然无法在外部访问。下面给你两种可行的解决办法:

方法1:提前声明索引变量

你可以在循环外部先定义一个可变的索引变量(用Option类型更安全),然后在循环内部更新它。这样循环结束后,这个变量依然在作用域内:

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;
    // 提前声明Option类型的变量,处理"可能找不到符合条件的索引"的情况
    let mut target_index = None;

    for (i, c) in instruction.chars().enumerate() {
        // 修正逻辑:原题中(是上楼+1,)是下楼-1,原代码写反啦
        if c == '(' {
            floor += 1;
        } else {
            floor -= 1;
        }

        if floor < 0 {
            target_index = Some(i + 1); // 题目要求的是第几个字符(从1开始计数)
            break;
        }
    }

    // 匹配Option处理两种情况
    match target_index {
        Some(idx) => println!("First position to go below floor 0: {}", idx),
        None => println!("Never went below floor 0"),
    }
}

这种方式的好处是逻辑清晰,同时用Option避免了无效默认值带来的潜在问题。

方法2:使用迭代器的find方法

Rust的迭代器提供了更简洁的风格来找到第一个符合条件的元素,结合enumerate可以直接拿到目标索引:

fn main() {
    let instruction = ")))(((()))))";
    let mut floor = 0;

    let target_index = instruction.chars().enumerate().find(|&(_, c)| {
        // 更新楼层计数
        if c == '(' {
            floor += 1;
        } else {
            floor -= 1;
        }
        // 判断是否满足"低于0层"的条件
        floor < 0
    }).map(|(i, _)| i + 1); // 转换为题目要求的1-based位置

    match target_index {
        Some(idx) => println!("First position to go below floor 0: {}", idx),
        None => println!("Never went below floor 0"),
    }
}

find方法会遍历迭代器,返回第一个满足闭包条件的元素,再通过map把0-based索引转换成题目需要的1-based位置,代码更简洁且符合Rust的迭代器习惯。

另外要提醒你两个原代码里的小问题:

  • 循环里误用了input变量,但你定义的是instruction,会导致编译错误;
  • 楼层变化的逻辑搞反了:Advent of Code 2015 Day1 Part2中,(代表上一层(floor+1),)代表下一层(floor-1),原代码的逻辑会导致结果错误哦。

内容的提问来源于stack exchange,提问作者Karl Anka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:09:55