2015-06-23 12 views
10

Che strano errore:Il risultato non ha un metodo chiamato "unwrap()"?

use std::collections::BTreeMap; 

struct MyStruct1; 
struct Error; 

fn get_res() -> Result<(MyStruct1, BTreeMap<String, String>), Error> { 
    Err(Error) 
} 

fn main() { 
    let res1 = get_res(); 
    assert!(res1.is_ok()); 
    assert_eq!("just for test", res1.unwrap()); //error 
} 

L'errore è:

error: no method named `unwrap` found for type `std::result::Result<(MyStruct1, std::collections::BTreeMap<std::string::String, std::string::String>), Error>` in the current scope 
    --> src/main.rs:13:38 
    | 
13 |  assert_eq!("just for test", res1.unwrap()); //error 
    |          ^^^^^^ 
    | 
    = note: the method `unwrap` exists but the following trait bounds were not satisfied: `Error : std::fmt::Debug` 
+0

provare 'assert_eq! (Res1.unwrap()," solo per test ");' – Virbhadrasinh

+1

possibile duplicato di [Tipo di risultato non implementa il metodo in ambito denominato \ unwrap \ '] (http://stackoverflow.com/questions/30787271/result-type-does-not-implement-method-in-scope-named-unwrap) –

risposta

15

Se si legge la documentazione per Result::unwrap, noterete che è sotto una piccola sezione chiamata:

impl<T, E> Result<T, E> 
    where E: Debug 

Ciò significa che i metodi in quella sezione esistono solo fintanto che i vincoli dati sono sati sfied.

L'unica ragione per cui unwrap non esiste è che Error non implementa Debug.

+0

Sapete se esiste una richiesta di funzionalità aperta contro rustc per elencare esplicitamente * perché * i metodi non sono stati considerati quando trova metodi con il nome giusto? Potrebbe essere difficile, per nomi comuni, anche se potrebbero essere priorizzati in alcuni casi e in numero limitato, tuttavia questo è qualcosa che ho trovato inestimabile in C++ SFINAE da quando Clang ha introdotto la funzione. –

+1

@MatthieuM. In realtà [ne ho aperto uno in risposta a questa domanda] (https://github.com/rust-lang/rust/issues/26516). –

+0

@DK .: Non posso commentare in questo momento, potresti voler menzionare che Clang lo gestisce con l'esclusione di SFINAE sui metodi template in C++, che è abbastanza simile (dato che SFINAE tratta dei metodi di selezione a seconda di alcune condizioni). Ciò non solo significa che la funzione è effettivamente implementabile, ma può anche fornire un'implementazione di riferimento per un potenziale implementatore. –

Problemi correlati