Ожидаемый тип String, найденный тип str, когда я явно сделал это String - PullRequest
0 голосов
/ 07 июня 2019
use std::collections::{HashMap, HashSet};

type Snapshot = HashMap<String, HashSet<String>>;

fn compare_snapshots(snapshot1: Snapshot, snapshot2: Snapshot, entry1: String, entry2: String) {}

fn main() {
    let snapshot1 = HashMap::new();
    let snapshot2 = HashMap::new();

    let entries1: HashSet<String> = snapshot1.keys().cloned().collect();
    let entries2: HashSet<String> = snapshot2.keys().cloned().collect();
    let entries: Vec<String> = entries1.union(&entries2).cloned().collect();

    for e1 in entries {
        for e2 in entries {
            if e1 < e2 {
                compare_snapshots(snapshot1, snapshot2, *e1.to_string(), *e2.to_string());
            }
        }
    }
}

И следующие ошибки:

error[E0308]: mismatched types
  --> src/main.rs:18:57
   |
18 |                 compare_snapshots(snapshot1, snapshot2, *e1.to_string(), *e2.to_string());
   |                                                         ^^^^^^^^^^^^^^^ expected struct `std::string::String`, found str
   |
   = note: expected type `std::string::String`
              found type `str`

error[E0308]: mismatched types
  --> src/main.rs:18:74
   |
18 |                 compare_snapshots(snapshot1, snapshot2, *e1.to_string(), *e2.to_string());
   |                                                                          ^^^^^^^^^^^^^^^ expected struct `std::string::String`, found str
   |
   = note: expected type `std::string::String`
              found type `str`

Почему я получил их, учитывая, что я явно сделал, дал entries тип Vec<String>?

1 Ответ

1 голос
/ 07 июня 2019

Ваш случай может быть уменьшен до

fn repro(_: String) {}

fn main() {
    repro(*"".to_string());
}

По какой-то причине вы разыменовываете String. String реализует Deref<Target = str>, поэтому вы явно попытались создать str. В конечном итоге это не сработает, потому что str не имеет размера, но вы сначала сталкиваетесь с несоответствием типов.

Снять звездочку:

fn repro(_: String) {}

fn main() {
    repro("".to_string());
}

Смотри также:

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