#Why does this need T to be Copy?

33 messages · Page 1 of 1 (latest)

kind badger
#

This is my code:

pub struct WithLock<T> {
	pub(crate) data: Mutex<T>,
}

impl<T> WithLock<T> {
	pub fn with_lock<F, U>(self, function: F) -> U
	where
		F: FnOnce(&mut T) -> U,
	{
		let mut lock = self.data.lock();
		function(&mut *lock)
	}

}

The issue I am facing, is when in another struct (using this WithLock struct) and attempting to do this:

    pub fn update<F>(&self, f: F) -> T
    where
        F: FnOnce(T) -> T,
    {
        let old = self.get();
        let new = f(old);
        self.set(new);
        new
    }

I get an error about the train bound T: std::marker::Copy not being satisfied. The get function is this:

	pub fn get(self) -> T
	where
		T: Copy,
	{
		self.data.with_lock(|s| *s)
	}

I'm aware I am making T Copy, but, I'm trying to figure out why the with_lock closure requires it to be Copy. Ideally, the value wouldn't have to be copy. Any ideas?

distant silo
#

returning *s requires that you can move or copy out of s

#

you can't ever move out of a reference so you're required to copy to write it like that

kind badger
#

oh yeah, forgot about that

distant silo
#

if you want to move out of a mutex you need to use into_inner on the mutex

kind badger
#

is there anyway to make it perform similarly without dereferencing

#

does into_inner perform a lock on a Mutex?

distant silo
#

no

#

the mutex cannot be locked, because you cannot have any references to it to call it

kind badger
#

🤔

distant silo
#

that's fine since get also requires that, unless your signature for get is wrong

kind badger
#

so you are saying locking the mutex in this scenario is just impossible

distant silo
#

not sure why you would want to lock it

kind badger
#

are we talking about the with_lock function or the get function

distant silo
#

get

kind badger
#

oh

#

i was talking about with_lock 😅

distant silo
#

I thought your problem was with get?

kind badger
#

yes, it was but i was wondering why with_lock required to do it

#

kinda misunderstanding

#

but thanks for the help, ima just make T copy

#

you need to use the get function in order for this MutexCell struct to work so

distant silo
#

um, ok

#

not sure why you don't just do self.data.into_inner()

kind badger
#

that kinda takes away the point of locking a mutex though

#

anyway - thanks for the help

distant silo
#

I guess your get signature is wrong then?

#

if it was supposed to be &self then sure

kind badger
#

get is &self

distant silo
#

ah

#

well, it wasn't in your post, but in that case it makes sense

kind badger
#

dont ask me how, no clue