Harrows and carving

Sorry for the newbie question. Error here

<anon>:30:5: 30:17 error: cannot borrow immutable borrowed content as mutable
<anon>:30     routing_node.put(3);
              ^^^^^^^^^^^^

I tried many things to get around this, but I know for sure that this is a simple mistake. Any help is greatly appreciated.

use std::thread;
use std::thread::spawn;
use std::sync::Arc;

struct RoutingNode {
  data: u16
}

impl RoutingNode {
  pub fn new() -> RoutingNode {
      RoutingNode { data: 0 }
}

pub fn run(&self) {
    println!("data : {}", self.data);
}

pub fn put(&mut self, increase: u16) {
    self.data += increase;
}
}

fn main() {
  let mut routing_node = Arc::new(RoutingNode::new());
  let mut my_node = routing_node.clone();
{
    spawn(move || {my_node.run(); });
}

routing_node.put(3);
}
+4
source share
1 answer

Arcdoes not allow changing its internal state, even if the container is marked as mutable. You must use one of Cell, RefCellor Mutex. Both Celland RefCellare not thread-safe, so you should use Mutex( last paragraph in the document ).

Example:

use std::thread::spawn;
use std::sync::Mutex;
use std::sync::Arc;

struct RoutingNode {
    data: u16,
}

impl RoutingNode {
    pub fn new() -> Self { RoutingNode { data: 0, } }  
    pub fn run(&self) { println!("data : {}" , self.data); }   
    pub fn put(&mut self, increase: u16) { self.data += increase; }
}

fn main() {
    let routing_node = Arc::new(Mutex::new(RoutingNode::new()));
    let my_node = routing_node.clone();
    let thread = spawn(move || { my_node.lock().unwrap().run(); });

    routing_node.lock().unwrap().put(3);
    let _ = thread.join();
}

Dummy

+5
source

All Articles