1

我无法解决一个明显的简单问题。

基本上我想将一个结构的实例推送到一个向量中,以便稍后将其取出,并通过调用为该结构实现的函数来修改对象。

为了简化案例,我创建了以下测试代码,这在我看来反映了相同的问题。

    let mut strings = Vec::new();
    strings.push("Hello".to_string());
    let string_option = strings.last();
    let string = string_option.unwrap();
    string.shrink_to(1);

这有编译错误

error[E0596]: cannot borrow `*string` as mutable, as it is behind a `&` reference
  --> src/main.rs:89:5
   |
88 |     let string = string_option.unwrap();
   |         ------ help: consider changing this to be a mutable reference: `&mut String`
89 |     string.shrink_to(1);
   |     ^^^^^^^^^^^^^^^^^^^ `string` is a `&` reference, so the data it refers to cannot be borrowed as mutable

然后我尝试了无穷无尽的变体,比如

    let mut strings = Vec::new();
    strings.push("Hello".to_string());
    let string_option = strings.last().as_mut();
    let string = string_option.unwrap();
    string.shrink_to(1);

... 或者 ...

    let mut strings = Vec::new();
    strings.push("Hello".to_string());
    let string_option = strings.last().as_deref_mut();
    let string = string_option.unwrap();
    string.shrink_to(1);

实际上,上面显示的代码是我最初想做的代码的简化。

struct Bar {
    data: Vec<String>
}

impl Bar {
    fn shrink_first(&mut self) {

        let s_opt = self.data.last().as_mut();  // s_opt is of type Option<&mut &String>

        let s = s_opt.unwrap(); // s is of type &mut & String
        s.shrink_to(1);
    }
}

上面的代码带来了以下错误...

error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:67:21
   |
67 |         let s_opt = self.data.last().as_mut();  // s_opt is of type Option<&mut &String>
   |                     ^^^^^^^^^^^^^^^^         - temporary value is freed at the end of this statement
   |                     |
   |                     creates a temporary which is freed while still in use
68 |
69 |         let s = s_opt.unwrap(); // s is of type &mut & String
   |                 ----- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

error[E0596]: cannot borrow `**s` as mutable, as it is behind a `&` reference
  --> src/main.rs:70:9
   |
70 |         s.shrink_to(1);
   |         ^^^^^^^^^^^^^^ cannot borrow as mutable

但在我看来,它总是有相同的根本原因,但我还没有弄清楚该怎么做。

4

1 回答 1

2

只需更改strings.last()strings.last_mut().

last()方法返回一个标准(不可变)引用(更准确地说,Option<&T>)。

为了能够改变向量中的最后一个String您需要通过.last_mut()

于 2022-02-09T18:16:36.730 回答