ожидаемая структура `std :: string :: String`, найденная структура` std :: str :: Split` - PullRequest
0 голосов
/ 26 мая 2019

Я делаю программу, которая вычисляет разницу между количеством дней в дате, введенных пользователем.Пока я могу заставить программу работать со строковым литералом, но не со строковым объектом.

use std::io;

fn main() {
    let mut date_1 = "22/8/2019".split("/");
    let mut date_2 = "30/8/2019".split("/");
    let vec_1: Vec<&str> = date_1.collect();
    let vec_2: Vec<&str> = date_2.collect();
    println!("{:#?}", vec_1);
    println!("{:#?}", vec_2);
    let my_int_2 = vec_2[0].parse::<i32>().unwrap();
    let my_int_1 = vec_1[0].parse::<i32>().unwrap();
    let result = my_int_2 - my_int_1;
    println!("The difference between two dates is: {}", result);
}

Вывод:

[
    "22",
    "8",
    "2019",
]
[
    "30",
    "8",
    "2019",
]
The difference between two dates is: 8

Я хочу спросить дату у пользователя:

use std::io;

fn main() {
    let mut date_1 = String::new();
    println!("Enter a date in (dd/mm/yy) format: ");
    io::stdin()
        .read_line(&mut date_1)
        .ok()
        .expect("Couldn't read line");

    let mut date_2 = String::new();
    println!("Enter a date in (dd/mm/yy) format: ");
    io::stdin()
        .read_line(&mut date_2)
        .ok()
        .expect("Couldn't read line");
    date_1 = date_1.split("/");
    date_2 = date_2.split("/");
    let vec_1: Vec<&str> = date_1.collect();
    let vec_2: Vec<&str> = date_2.collect();
    println!("{:#?}", vec_1);
    println!("{:#?}", vec_2);
    let my_int_2 = vec_2[0].parse::<i32>().unwrap();
    let my_int_1 = vec_1[0].parse::<i32>().unwrap();
    let result = my_int_2 - my_int_1;
    println!("The difference between two dates is: {}", result);
}

Вывод:

   Compiling twentythree v0.1.0 (C:\Users\Muhammad.3992348\Desktop\rust\hackathon\twentythree)
error[E0308]: mismatched types
  --> src\main.rs:15:14
   |
15 |     date_1 = date_1.split("/");
   |              ^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found struct `std::str::Split`
   |
   = note: expected type `std::string::String`
              found type `std::str::Split<'_, &str>`

error[E0308]: mismatched types
  --> src\main.rs:16:14
   |
16 |     date_2 = date_2.split("/");
   |              ^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found struct `std::str::Split`
   |
   = note: expected type `std::string::String`
              found type `std::str::Split<'_, &str>`

error[E0599]: no method named `collect` found for type `std::string::String` in the current scope
  --> src\main.rs:19:35
   |
19 |     let vec_1: Vec<&str> = date_1.collect();
   |                                   ^^^^^^^
   |
   = note: the method `collect` exists but the following trait bounds were not satisfied:
           `&mut std::string::String : std::iter::Iterator`
           `&mut str : std::iter::Iterator`

error[E0599]: no method named `collect` found for type `std::string::String` in the current scope
  --> src\main.rs:20:35
   |
20 |     let vec_2: Vec<&str> = date_2.collect();
   |                                   ^^^^^^^
   |
   = note: the method `collect` exists but the following trait bounds were not satisfied:
           `&mut std::string::String : std::iter::Iterator`
           `&mut str : std::iter::Iterator`

error: aborting due to 4 previous errors

Some errors occurred: E0308, E0599.
For more information about an error, try `rustc --explain E0308`.
error: Could not compile `twentythree`.

To learn more, run the command again with --verbose.

Как преобразовать строковый объект в строковый литерал или любую другую войну, которая запускает программу.

1 Ответ

3 голосов
/ 26 мая 2019

Проблема заключается в следующем:

let mut date_1 = String::new(); /* type: std::string::String */
// ...
date_1 = date_1.split("/"); /* type: std::str::Split<'_, &str> */

Вы объявили переменную одного типа (String), но пытаетесь присвоить ее другому типу (std::str::Split).


Один из способов решения этой проблемы "Rust-y", как правило, заключается в переопределении переменной с тем же именем:

let date_1 = String::new(); /* type: std::string::String */
// ...
let date_1 = date_1.split("/"); /* type: std::str::Split<'_, &str> */

Вторая date_1 - это другая переменная (следовательно, она может иметь другой тип), но она имеет то же имя, что и прежняя переменная, поэтому она "затеняет" прежнюю переменную (то есть вы не можете ссылаться на нее по имени больше).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...