Is it possible to get a value from a collection and apply a method to it which accepts only self and not &self?
Minimal Working Example
What I would like to write is something akin to:
use std::collections::HashMap;
fn get<B>(key: i32, h: HashMap<i32, Vec<(i32, B)>>) -> i32 where B: Into<i32> {
let v: &Vec<(i32, B)> = h.get(&key).unwrap();
let val: &B = v.first().unwrap().1;
// Do something to be able to call into
// I only need the value as read-only
// Does B have to implement the Clone trait?
return val.into();
}
I have tried in vain to dribble mut here and there to try to appease compiler error after compiler error, but this is really a fool's errand.
use std::collections::HashMap;
fn get<B>(key: i32, mut h: HashMap<i32, Vec<(i32, B)>>) -> i32 where B: Into<i32> {
let mut v: &Vec<(i32, B)> = h.get_mut(&key).unwrap();
let ref mut val: B = v.first_mut().unwrap().1;
return (*val).into();
}
Is this sort of thing even possible or does B have to implement the Clone trait?
I've also tried:
- Unsafe
- Raw pointers
I've not tried:
Box- Other Rust constructs that I have not encountered, I mention this to explicitly state that I have not omitted any approaches that I know of.