this post was submitted on 16 Sep 2024
51 points (100.0% liked)

Rust

5771 readers
50 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
[–] lolcatnip@reddthat.com 0 points 3 days ago (5 children)

try_lock already exists; it's called lock. I just want a more convenient name and I want the name of the new method to be lock, but that ship has sailed.

[–] BB_C@programming.dev 3 points 2 days ago* (last edited 2 days ago) (4 children)

if you're really that bothered..

use std::sync::{Mutex, MutexGuard};

trait ULock<'a> {
    type Guard;
    fn ulock(&'a self) -> Self::Guard;
}

impl<'a, T: 'a> ULock<'a> for Mutex<T> {
    type Guard = MutexGuard<'a, T>;
    fn ulock(&'a self) -> Self::Guard {
      self.lock().unwrap()
    }
}

or use a wrapper struct, if you really really want the method to be called exactly lock.

[–] lolcatnip@reddthat.com 1 points 2 days ago* (last edited 2 days ago) (3 children)

I think a better solution would be to add a method called something like ulock that does a combined lock and unwrap.

My concern with lock+unwrap is only partly because of convenience; I also didn't like it because I think it's a bad idea to get people used to casually calling unwrap, because it tends to hide inadequate error handing.

Now that I think about it, I don't like how unwrap can signal either "I know this can't fail", "the possible error states are too rare to care about" or "I can't be bothered with real error handing right now". In one or two of those cases you want to leave it in my production code, and in the last you want to audit all instances and replace them with proper error handing. Using the same function for all three cases makes that difficult.

[–] 5C5C5C@programming.dev 1 points 1 day ago

Best practice when using .unwrap() in production code is to put a line of documentation immediately above the use of .unwrap() that describes the safety invariants which allow the unwrap to be safe.

Since code churn could eventually cause those safety invariants to be violated, I think it's not a bad thing for a blunt audit of .unwrap() to bring your attention to those cases and prompt to reevaluate if the invariants are still satisfied.

load more comments (2 replies)
load more comments (2 replies)
load more comments (2 replies)