Skip to content

Suggest to replace Option::as_ref().cloned() with Option::replace() #12009

@psychon

Description

@psychon

What it does

Search for code doing .as_ref().cloned() on an Option<T> and suggests to just use .clone() directly.

Advantage

  • More direct / explicit code that is hopefully easier to understand

Drawbacks

🤷

Example

Self-contained example:

fn foo(bar: &Option<Vec<u8>>) -> Option<Vec<u8>> {
    bar.as_ref().cloned()
}

Could be written as:

fn foo(bar: &Option<Vec<u8>>) -> Option<Vec<u8>> {
    bar.clone()
}

Recently, I was looking at some code in winit and failed to understand this code. There is a cache using Mutex<Option<...>>. The code here tries to either copy the value contained in the cache or fill the cache.

The first part of my problem was that I somehow thought that .as_ref().cloned() does something to the inner contents and not the Option directly

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions