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

时间:2018-08-29 18:11:26

标签: rust clap

我正在尝试传递String来鼓掌的生成器方法:

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,也会收到类似的错误。我正在努力了解此错误的起因以及使用签名pub fn about<S: Into<&'b str>>(self, about: S) -> Self拍手的原因。

1 个答案:

答案 0 :(得分:3)

在给定的Into<&str>约束下,编译器无法将String&String直接转换为请求的字符串切片。对于字符串切片,From<String>From<&String>都没有这样的实现。从拥有的字符串或类似字符串的值到切片的转换通常是通过其他特性完成的。

相反,您可以:

  1. 使用String::as_str(),它始终提供&str;
  2. AsRef特性调用as_ref(),导致编译器为AsRef<str>选择实现String
  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)