/playground.rs Secret
Created
April 4, 2025 23:40
Code shared from the Rust Playground
This file contains 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; | |
use std::rc::{Rc,Weak}; | |
struct CustomStruct { | |
name: String, | |
} | |
impl CustomStruct { | |
fn new(name: String) -> CustomStruct { | |
CustomStruct { | |
name, | |
} | |
} | |
} | |
struct ListData { | |
items: Vec<Rc<CustomStruct>>, | |
filtered: RefCell<Vec<Weak<CustomStruct>>> | |
} | |
impl ListData { | |
fn new(items: Vec<Rc<CustomStruct>>) -> ListData { | |
ListData { | |
items, | |
filtered: RefCell::new(vec![]) | |
} | |
} | |
fn filter(&self, value: &str) { | |
*self.filtered.borrow_mut() = self.items.iter() | |
.filter(|i| i.name.contains(value)) | |
.map(|r| Rc::downgrade(r)) | |
.collect(); | |
} | |
fn print_filtered(&self) { | |
self.filtered.borrow().iter().for_each(|i| println!("Filtered value {}", i.upgrade().unwrap().name)); | |
} | |
} | |
fn main() { | |
let data = ListData::new( | |
vec!( | |
Rc::new(CustomStruct::new("Alice".to_string())), | |
Rc::new(CustomStruct::new("Bob".to_string())), | |
Rc::new(CustomStruct::new("Charlie".to_string())) | |
) | |
); | |
data.filter("B"); | |
data.print_filtered(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment