I understand that a stack allocated value cannot be returned, but is it possible to return a reference to a HashMap value? If this is not possible I'll have to do another lookup in another function.
use std::cell::RefCell;
use std::collections::HashMap;
struct File();
struct FS {
files: RefCell<HashMap<u64, File>>
}
impl FS {
fn new() -> FS {
FS {
files: RefCell::new(HashMap::<u64, File>::new())
}
}
fn return_ref_from_collection(&mut self) -> &File {
let file = File();
self.files.borrow_mut().insert(1, file);
let f = self.files.borrow().get(&1).unwrap();
// ... do thins with f
f // => returns a value referencing data owned by the current function
// but I think where f is referencing is not owned by this function
}
}
fn main() {
let mut fs = FS::new();
fs.return_ref_from_collection();
}
I agree it's somewhat weird to put RefCell here. Anyway since you have an unique access(&mut) to the refcell so you don't need to care about shared mutability.
let map = self.file.get_mut();
map.insert(1, File);
map.get(&1).unwrap()