Search code examples
rustcompiler-warningsclap

How to stop warnings about parentheses required by clap macros?


With this code:

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
    #[arg(short, long, default_value_t = ("/dev/ttyUSB3".to_string()))]
    modem_path: String,

    ...
}

I get a warning:

warning: unnecessary parentheses around assigned value
  --> src/main.rs:30:42
   |
30 |     #[arg(short, long, default_value_t = ("/dev/ttyUSB3".to_string()))]
   |                                          ^                          ^
   |
   = note: `#[warn(unused_parens)]` on by default
help: remove these parentheses
   |
30 -     #[arg(short, long, default_value_t = ("/dev/ttyUSB3".to_string()))]
30 +     #[arg(short, long, default_value_t = "/dev/ttyUSB3".to_string())]
   |

If I remove the parens, I get an error:

error: expected `,`
  --> src/main.rs:30:56
   |
30 |     #[arg(short, long, default_value_t = "/dev/ttyUSB3".to_string())]
   |                                                        ^

I have many other more complex arguments with the same issue, e.g.

#[arg(short, long, default_value_t = ("127.0.0.1:2947".parse().unwrap()))]
gpsd_socket: SocketAddr,

How can I make this code error- and warning-free?


Solution

  • It's hard to judge whether this is a bug of rustc (warning in macros even when this is incorrect) or of clap (expanding to a code including unnecessary parentheses) but this is definitely not your fault. Unfortunately, it seems the best you can do is to #[allow(unused_parens)] for the whole module. You can separate the struct into a different module to minimize the impact:

    #[allow(unused_parens)]
    mod args {
        #[derive(Parser, Debug)]
        #[command(author, version, about, long_about = None)]
        pub(super) struct Args {
            #[arg(short, long, default_value_t = ("/dev/ttyUSB3".to_string()))]
            pub(super) modem_path: String,
        
            // ...
        }
    }