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

Rust报错:cannot borrow `*s` as mutable,求问题原因及解决方法

问题分析与解决

错误原因

Chars迭代器的next()方法需要可变引用(&mut self)——因为调用next()会修改迭代器的内部状态(移动其内部指针到下一个字符)。而你通过&all_iterators遍历集合时,拿到的是&Chars类型的不可变引用,无法满足next()对可变借用的要求,因此触发编译错误。

修正后的代码

let mut all_iterators: Vec<std::str::Chars> = Vec::new();
for s in strings {
    let a = s.chars();
    all_iterators.push(a);
}

// 用String而非&str,因为需要动态追加字符
let mut common_str = String::new();
loop {
    let mut common_char: Option<char> = None;

    // 遍历可变引用的迭代器集合,获取&mut Chars以调用next()
    for s in &mut all_iterators {
        match s.next() {
            Some(c) => {
                if common_char.is_none() {
                    common_char = Some(c);
                } else if common_char != Some(c) {
                    // 字符不匹配,无公共前缀
                    common_char = None;
                    break;
                }
            }
            None => {
                // 某个字符串已遍历完毕,终止循环
                common_char = None;
                break;
            }
        }
    }

    match common_char {
        Some(c) => common_str.push(c),
        None => break, // 无更多公共字符,退出循环
    }
}

关键修改说明

  1. 可变遍历集合:将for s in &all_iterators改为for s in &mut all_iterators,这样每个迭代器都以可变引用(&mut Chars)的形式被访问,允许调用需要修改自身状态的next()方法。
  2. 改用String存储结果:原代码中common_str是不可变的&str,无法追加字符,改为String后可以动态构建公共前缀。
  3. 补充循环终止逻辑:当某个字符串遍历完成,或者出现不匹配的字符时,终止循环,避免无限执行。

内容的提问来源于stack exchange,提问作者Moiz Sohail

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:50:21