Re: [PATCH v6] rust: sync: add #[must_use] to Lock::try_lock

Boqun Feng
2024-12-15T20:05:04Z

Hi Jason,

On Thu, Dec 12, 2024 at 10:47:53AM -0500, Jason Devers wrote:
> The `Lock::try_lock` function returns an `Option<Guard<...>>`, but it
> currently does not issue a warning if the return value is unused.
> To avoid potential bugs, the `#[must_use]` annotation is added to ensure proper usage.
>
> Note that `T` is `#[must_use]` but `Option<T>` is not.
> For more context, see: https://github.com/rust-lang/rust/issues/71368.
>
> Suggested-by: Alice Ryhl <aliceryhl@google.com>
> Link: https://github.com/Rust-for-Linux/linux/issues/1133

I think you could add Alice's Reviewed-by from the previous version:

https://lore.kernel.org/rust-for-linux/CAH5fLghjR4fctjoLT9Zom3drNMQ6vdE9hUTnZZ4Ms1qQHGFe=A@mail.gmail.com/

or you have any reason that you need another "Reviewed-by" tag?

(No need to send a new version, I'm just making sure you and Alice both
agree the "Reviewed-by" tag still applies to this patch.)

Regards,
Boqun

> Signed-off-by: Jason Devers <dev.json2@gmail.com>
> ---
> rust/kernel/sync/lock.rs | 2 ++
> 1 file changed, 2 insertions(+)
>
> diff --git a/rust/kernel/sync/lock.rs b/rust/kernel/sync/lock.rs
> index 41dcddac69e2..aacc227536cb 100644
> --- a/rust/kernel/sync/lock.rs
> +++ b/rust/kernel/sync/lock.rs
> @@ -147,6 +147,8 @@ pub fn lock(&self) -> Guard<'_, T, B> {
> /// Tries to acquire the lock.
> ///
> /// Returns a guard that can be used to access the data protected by the lock if successful.
> + // `Option<T>` is not `#[must_use]` even if `T` is, thus the attribute is needed here.
> + #[must_use = "if unused, the lock will be immediately unlocked"]
> pub fn try_lock(&self) -> Option<Guard<'_, T, B>> {
> // SAFETY: The constructor of the type calls `init`, so the existence of the object proves
> // that `init` was called.
> --
> 2.44.2
>