Как передать строку в метод, принимающий Into <& str>? - PullRequest
0 голосов
/ 29 августа 2018

Я пытаюсь передать 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`

Живой пример

Я получаю похожую ошибку, если передам &description. Я изо всех сил пытаюсь понять причину этой ошибки и причины хлопать с помощью подписи pub fn about<S: Into<&'b str>>(self, about: S) -> Self.

1 Ответ

0 голосов
/ 29 августа 2018

При данном (необычном) ограничении Into<&str> компилятор не может превратить String или &String непосредственно в запрошенный фрагмент строки. Не существует такой реализации ни From<String>, ни From<&String> для среза строки. Преобразование из принадлежащей строки или строкового значения в срез обычно выполняется с помощью других признаков.

Вместо этого вы можете:

  1. Используйте String::as_str(), что всегда обеспечивает &str;
  2. Позвоните as_ref() из черты AsRef, что заставит компилятор выбрать реализацию 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)
...