James Smith
James Smith

Reputation: 319

How to lock a Rust struct the way a struct is locked in Go?

I'm trying to learn how to do locks in Rust the way they work in Go. With Go I can do something like:

type Info struct {
    sync.RWMutex
    height    uint64 
    verify bool
}

If I have some function/method acting on info I can do this:

func (i *Info) DoStuff(myType Data) error {
    i.Lock()
    //do my stuff
}

It seems like what I need is the sync.RWMutex, so this is what I have tried:

pub struct Info {
    pub lock: sync.RWMutex,
    pub height: u64,
    pub verify: bool,
}

Is this the correct approach? How would I proceed from here?

Upvotes: 1

Views: 2383

Answers (1)

Shepmaster
Shepmaster

Reputation: 430368

Don't do it the Go way, do it the Rust way. Mutex and RwLock are generic types; you put the data to be locked inside of them. Later, you access the data through the lock guard. When the lock guard goes out of scope, the lock is released:

use std::sync::RwLock;

#[derive(Debug, Default)]
struct Info {
    data: RwLock<InfoData>,
}

#[derive(Debug, Default)]
struct InfoData {
    height: u64,
    verify: bool,
}

fn main() {
    let info = Info::default();
    let mut data = info.data.write().expect("Lock is poisoned");
    data.height += 42;
}

The Go solution is suboptimal as nothing forces you to actually use the lock; you can trivially forget to acquire the lock and access data that should only be used when locked.

If you must lock something that isn't the data, you can just lock the empty tuple:

use std::sync::RwLock;

#[derive(Debug, Default)]
struct Info {
    lock: RwLock<()>,
    height: u64,
    verify: bool,
}

fn main() {
    let mut info = Info::default();
    let _lock = info.lock.write().expect("Lock is poisoned");
    info.height += 42;
}

See also:

Upvotes: 18

Related Questions