Can't get clap App .author() to accept a String or &str

I've hit an annoying problem with clap: I can't get it to output the 'author' string that I want. Here's an example:

extern crate chrono;
extern crate clap;
use chrono::prelude::*;
use clap::{Arg, App};
fn main() {
    let year = chrono::Utc::now().year();
    let year = if year == 2017 { "2017".to_string() } else
                               { format!("2017-{}", year - 2000) };
    let copyright = format!("Copyright © {}. Me", year);
    println!("{}", copyright);
    
    let matches = App::new("My App")
        .author(copyright)
        .arg(Arg::with_name("debug").short("D").long("debug"))
        .get_matches();
    println!("{:?}", matches)
}

And here's the error:

error[E0277]: the trait bound `&str: std::convert::From<std::string::String>` is not satisfied
  --> src/main.rs:13:10
   |
13 |         .author(copyright)
   |          ^^^^^^ the trait `std::convert::From<std::string::String>` is not implemented for `&str`
   |
   = note: required because of the requirements on the impl of `std::convert::Into<&str>` for `std::string::String`

Naturally I tried &copyright but that didn't help either.

I'm guessing that I need to use a trait, but I don't know which one!

Code in the Playground

You can try .author(&copyright[..]) or .author(&*copyright), since deref coercions don't trigger in a generic context (see the signature of copyright(): its argument is generic).

From the doc, it expects something that can be converted into a &str.

Try using &copyright.

Or alternatively you can convert to &str by using .as_str()

As I mentioned I tried &copyright but it didn't work. Your .as_str() worked fine though--thanks.

1 Like