如何在 Rust 中更新结构内的集合?

问题描述 投票:0回答:1

可能这个问题已经被问过,也许措辞不同,但我找不到它。如果因此而关闭,抱歉,但我之前确实尝试过。

其实问题很简单:

use std::collections::BTreeSet;

pub struct Service {
    blobs: BTreeSet<u16>,
}

impl Service {
    fn new() -> Self {
        let bt: BTreeSet<u16> = BTreeSet::new();
        Self { blobs: bt }
    }

    fn insert(&self, val: u16) -> bool {
        &self.blobs.insert(val);
        true
    }
    fn print(&self) {
        println!("{}", self.blobs.len());
    }
}
fn main() {
    let s: Service = Service::new();
    s.print();
    s.insert(4);
    s.print();
}

编译时,我得到:

^^^^^^^^^^ 
自己
is a
&
 reference, so the data it refers to cannot be borrowed as mutable

我在这里理解的是,实际上,我不能只更新树集,因为它是不可变的。

所以我尝试了

pub struct Service {
    blobs: &'static mut BTreeSet<u16>,
}

  fn new() -> Self {
        let bt: &mut BTreeSet<u16> = &mut BTreeSet::new();
        Self { blobs: bt }
    }

但这会产生

creates a temporary value which is freed while still in use
(虽然原来的错误仍然存在,所以现在我有两个......)

我知道我应该以某种方式使

BTreeSet
可变,但是如何实现呢?

rust struct mutable
1个回答
0
投票

RTFEM

大多数时候,错误消息只是告诉你如何修复代码,所有的 rust 编译器都是如此。

PS *******************> cargo run --bin fuck_around
   Compiling fuck_around v0.1.0 (*******************)
error[E0596]: cannot borrow `self.blobs` as mutable, as it is behind a `&` reference
  --> fuck_around\src/main.rs:14:9
   |
14 |         self.blobs.insert(val)
   |         ^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
   |
help: consider changing this to be a mutable reference
   |
13 |     fn insert(&mut self, val: u16) -> bool {
   |               ~~~~~~~~~

For more information about this error, try `rustc --explain E0596`.
error: could not compile `fuck_around` (bin "fuck_around") due to 1 previous error

已修复

use std::collections::BTreeSet;

pub struct Service {
    blobs: BTreeSet<u16>,
}

impl Service {
    fn new() -> Self {
        let bt: BTreeSet<u16> = BTreeSet::new();
        Self { blobs: bt }
    }

    fn insert(&mut self, val: u16) -> bool {
        self.blobs.insert(val)
    }
    fn print(&self) {
        println!("{}", self.blobs.len());
    }
}
fn main() {
    let mut s: Service = Service::new();
    s.print();
    s.insert(4);
    s.print();
}
© www.soinside.com 2019 - 2024. All rights reserved.