Created
April 25, 2024 23:54
-
-
Save computermouth/db713dfaf489f5714ecced993d195685 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::cell::RefCell; | |
enum Type { | |
Add, | |
Sub | |
} | |
struct Entity { | |
t: Type, | |
i: i32, | |
} | |
impl Entity { | |
pub fn update(&self, own_id: usize, v: &Vec<RefCell<Entity>>){ | |
for i in 0..v.len() { | |
if i == own_id { | |
continue; | |
} | |
match self.t { | |
Type::Add => { | |
let mut ti = v[i].borrow_mut(); | |
ti.i = ti.i + 1; | |
} | |
Type::Sub => { | |
let mut ti = v[i].borrow_mut(); | |
ti.i = ti.i - 1; | |
} | |
} | |
} | |
} | |
} | |
fn main() { | |
let entities = vec![ | |
RefCell::new(Entity{t: Type::Add, i: 0}), | |
RefCell::new(Entity{t: Type::Add, i: 0}), | |
RefCell::new(Entity{t: Type::Add, i: 0}), | |
RefCell::new(Entity{t: Type::Sub, i: 0}), | |
RefCell::new(Entity{t: Type::Sub, i: 0}), | |
]; | |
for i in 0..entities.len() { | |
let e = entities[i].borrow_mut(); | |
e.update(i, &entities); | |
println!("[{}]: {}", i, e.i); | |
} | |
} | |
/* OUTPUT | |
## before adding in the own_id check | |
$ cargo run | |
Compiling rustscratch v0.1.0 (/home/byoung/tmp/rustscratch) | |
Finished dev [unoptimized + debuginfo] target(s) in 0.13s | |
Running `target/debug/rustscratch` | |
thread 'main' panicked at src/main.rs:18:39: | |
already borrowed: BorrowMutError | |
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace | |
## after adding in the own_id check | |
$ cargo run | |
Compiling rustscratch v0.1.0 (/home/byoung/tmp/rustscratch) | |
Finished dev [unoptimized + debuginfo] target(s) in 0.12s | |
Running `target/debug/rustscratch` | |
[0]: 0 | |
[1]: 1 | |
[2]: 2 | |
[3]: 3 | |
[4]: 2 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment