1
votes

This simple function locks a f64 and updates the value

use std::sync::Mutex;

fn bar() {
    let a = Mutex::new(1.0);
    let mut b = a.lock().unwrap();
    *b = 2.0;
    foo(a, 3.0);
}

I would like to encapsulate the behaviour into a function but I cannot figure out how to specify the where clause for T

fn foo<T, V>(lockable_param: T, value: V)
// where
//    T: Mutex??,
{
    let mut lock = lockable_param.lock().unwrap();
    *lock = value;
}
1
1) Did you mean .lock().unwrap()? 2) How are V and T related, why are you trying to assign a V where a T would be expected? In your first example, both T and V seem to be the same type f64.Andrey Tyukin
1) yes - fixed 2) In this case yes, but in my real code, V is not the underlying typeDelta_Fore

1 Answers

1
votes

You don't need as many parameters, just use Mutex<T> and T for parameters. I presume you will need to receive a reference and not a value since you are not returning anything. This should work:

use std::sync::Mutex;

fn bar() {
    let a = Mutex::new(1.0);
    let mut b = a.lock().unwrap();
    *b = 2.0;
    foo(&a, 3.0);
}

fn foo<T>(lockable_param: &Mutex<T>, value: T) {
    let mut lock = lockable_param.lock().unwrap();
    *lock = value;
}