Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created October 11, 2018 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/f121f07871273197f4a9c1c6132b2f8e to your computer and use it in GitHub Desktop.
Save rust-play/f121f07871273197f4a9c1c6132b2f8e to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#![allow(dead_code)]
#![allow(unused_mut)]
use std::collections::HashMap;
use std::sync::Mutex;
#[derive(Debug)]
struct Student {
id: u32,
name: String,
age: u32,
}
impl Student {
fn new(id: u32, name: &str, age: u32) -> Self {
Student {
id,
name: name.to_string(),
age,
}
}
fn update_name(&mut self, name: &str) {
self.name = name.to_string();
}
}
fn no_mutex() {
// data tiene que ser mutable para poder modificar cada estudiante
let mut data = vec![
Student::new(0, "Alice", 18),
Student::new(1, "Bob", 23),
Student::new(2, "Charlie", 21),
Student::new(3, "David", 19),
];
// El indice es un hashmap con referencias a estudiantes
let mut index: HashMap<u32, &Student> = HashMap::new();
// Poblamos el índice
for student in &data {
index.insert(student.age, student);
}
// Buscamos al segundo estudiante usando el índice
println!("{:?}", index.get(&23));
// Ahora tratamos de modificar el nombre de ese mismo estudante
// pero vamos a fallar porque el índice tiene referencias inmutables.
// descomenten la linea y traten de correrlo
// data[1].update_name("Bill");
// println!("{:?}", index.get(&23));
}
fn with_mutex() {
// data tiene que ser mutable para poder modificar cada estudiante
let mut data = vec![
Mutex::new(Student::new(0, "Alice", 18)),
Mutex::new(Student::new(1, "Bob", 23)),
Mutex::new(Student::new(2, "Charlie", 21)),
Mutex::new(Student::new(3, "David", 19)),
];
// El indice es un hashmap con referencias a los mutex
let mut index: HashMap<u32, &Mutex<Student>> = HashMap::new();
// Poblamos el índice
for mutex in &data {
// bloqueamos para poder leer al estudiante
let student = mutex.lock().unwrap();
index.insert(student.age, mutex);
}
// Buscamos al segundo estudiante usando el índice
println!("{:?}", index.get(&23));
// Ahora modificamos el nombre de ese mismo estudante
data[1].lock().unwrap().update_name("Bill");
// y tambien podemos volver a buscarlo con el indice
println!("{:?}", index.get(&23));
}
fn main() {
no_mutex();
with_mutex();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment