I want to get a value from a HashMap, or default to the last value in the HashMap, but it's values
returns a reference which I cannot clone:
let db_def: Option<&Mutex<Option<rusqlite::Connection>>> = by_name
.get(&db_name)
.or(by_name.values().collect::<Vec<&Mutex<Option<rusqlite::Connection>>>>().last());
|
189 | .or(by_name.values().collect::<Vec<&Mutex<Option<rusqlite::Connection>>>>().last());
| -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::sync::Mutex`, found reference
| |
| arguments to this function are incorrect
|
= note: expected enum `std::option::Option<&std::sync::Mutex<std::option::Option<Connection>>>`
found enum `std::option::Option<&&std::sync::Mutex<std::option::Option<Connection>>>`
Is there some way to use or
such that I can pass it a reference? into_values
isn't an option since I cannot transfer ownership of this state.
The work around is that I pre-define the default, but then I'm unnecessarily processing a large Vec
. I'd like to only get a default lazily, when the requested key isn't found. Is that possible?
let available = by_name.values().collect::<Vec<&Mutex<Option<rusqlite::Connection>>>>();
let db = if let Some(existing) = by_name.get(&db_name) {
existing
} else {
available.last().ok_or("no dbs exist")?
};