错误[E0502]:不能将`char_array`借用为可变,因为它也被借用为不可变的

时间:2017-11-02 14:27:29

标签: rust

我正在编写一个小程序来识别字符串中的第一个重复出现的字符:

error[E0502]: cannot borrow `char_array` as mutable because it is also borrowed as immutable
  --> src/main.rs:31:9
   |
25 |         let mut some_val = char_array.iter().find(|&&c| c == each_char);
   |                            ---------- immutable borrow occurs here
...
31 |         char_array.push(each_char);
   |         ^^^^^^^^^^ mutable borrow occurs here
32 |         println!(" The charcater is {:?}", some_val);
33 |     }
   |     - immutable borrow ends here

错误:

/**
 * @deprecated use {@link HSSFColorPredefined} instead
 */
@Deprecated
@Removal(version="3.18")
public static class BRIGHT_GREEN extends HSSFColorRef {
    private static final HSSFColorPredefined ref = HSSFColorPredefined.BRIGHT_GREEN;
    public static final short index = ref.getIndex();
    public static final int index2 = ref.getIndex2();
    public static final short[] triplet = ref.getTriplet();
    public static final String hexString = ref.getHexString();
    public BRIGHT_GREEN() { super(ref); }
}

我做错了什么?如果有人能够解释它,那将是非常有帮助的,因为我发现难以理解可变借用的概念。

1 个答案:

答案 0 :(得分:2)

char_array.iter().find(|&&c| c == each_char)的返回类型是Option<&char>;指向char_array中原始项目的引用。然后,您尝试修改char_array,这可能会使任何引用无效。之后,您尝试通过打印来访问现在可能无效的值。

在像C或C ++这样的语言中,这段代码是允许的,但偶尔会崩溃,损坏数据,允许任意代码执行,或者吃掉你的衣服。

最懒的解决方案是重新排序println并在some_val应居住的地方添加一组额外的括号。 (将来我们将拥有 Non-Lexical Lifetimes 并且不需要额外的括号):

{
    let mut some_val = char_array.iter().find(|&&c| c == each_char);

    match some_val {
        Some(ch) => return each_char,
        _ => println!("do nothing"),
    }
    println!(" The character is {:?}", some_val);
}

char_array.push(each_char);

你也可以克隆这个值,打破some_valchar_array之间的关系:

let mut some_val = char_array.iter().find(|&&c| c == each_char).cloned();

另见: