rust-lang / rust-lang/rust-clippy

needless_pass_by_value and closures

Open
#2,434 2 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug E-medium L-correctness
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Given this example code:

extern crate clap;
use clap::{App, Arg};

fn my_validator(v: String) -> Result<(), String> {
    if v.len() > 5 {
        Err("no".into())
    } else {
        Ok(())
    }
}

fn main() {
    let matches = App::new("example")
        .arg(Arg::with_name("myarg")
            .validator(my_validator))
        .get_matches();

    println!("{:?}", matches);
}

Clippy suggests changing v: String to v: &str but my_validator is given to Arg::validator which requires String.

warning: this argument is passed by value, but not consumed in the function body
 --> src/main.rs:4:20
  |
4 | fn my_validator(v: String) -> Result<(), String> {
  |                    ^^^^^^ help: consider changing the type to: `&str`
  |
  = note: #[warn(needless_pass_by_value)] on by default
  = help: for further information visit https://rust-lang-nursery.github.io/rust-clippy/v0.0.185/index.html#needless_pass_by_value
error[E0631]: type mismatch in function arguments
  --> src/main.rs:15:14
   |
4  | fn my_validator(v: &str) -> Result<(), String> {
   | ---------------------------------------------- found signature of `for<'r> fn(&'r str) -> _`
...
15 |             .validator(my_validator))
   |              ^^^^^^^^^ expected signature of `fn(std::string::String) -> _`

error: aborting due to previous error

Could clippy investigate the function usage in situations like this to prevent suggestions such as this?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the implementation of the needless_pass_by_value lint and inspect how it handles function items passed to APIs such as Arg::validator. Reproduce the reported Rust example and trace the lint's suggestion against the required String signature. Done means the lint avoids an invalid &str suggestion in this case, with regression coverage for the behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.