代码之家  ›  专栏  ›  技术社区  ›  JMAA

如何将字符串传递给接受<str>的方法?

  •  1
  • JMAA  · 技术社区  · 8 年前

    String 要使用clap的生成器方法,请执行以下操作:

    extern crate clap; // 2.32.0
    
    use clap::App;
    
    const NAME: &'static str = "example";
    const DESC_PART_1: &'static str = "desc";
    const DESC_PART_2: &'static str = "ription";
    
    fn main() {
        let description: String = format!("{}{}", DESC_PART_1, DESC_PART_2);
        let matches = App::new(NAME).about(description).get_matches();
    }
    

    我得到一个错误:

    error[E0277]: the trait bound `&str: std::convert::From<std::string::String>` is not satisfied
      --> src/main.rs:11:34
       |
    11 |     let matches = App::new(NAME).about(description).get_matches();
       |                                  ^^^^^ 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`
    

    Live example

    &description . 我正在努力理解这个错误的起源,以及使用这个签名的clap背后的原因 pub fn about<S: Into<&'b str>>(self, about: S) -> Self .

    1 回复  |  直到 8 年前
        1
  •  3
  •   E_net4 Tunn    8 年前

    具有给定的(不寻常的)约束 Into<&str> ,编译器无法打开 String 或者 &String From<String> From<&String> ,表示字符串片段。从拥有的字符串或类似字符串的值到切片的转换通常通过其他特性完成。

    相反,您可以:

    1. String::as_str() ,它总是提供 &str ;
    2. as_ref() AsRef trait,引导编译器选择实现 AsRef<str> 对于 ;
    3. 或者重新借用字符串,从而强制转换为 &str公司 .
    let matches = App::new(NAME).about(description.as_str()).get_matches(); // (1)
    let matches = App::new(NAME).about(description.as_ref()).get_matches(); // (2)
    let matches = App::new(NAME).about(&*description).get_matches(); // (3)
    
    推荐文章