2015-03-23 3 views
5

ho seguito il codice per aprire un file da Rust by Example:Impossibile leggere il contenuto dei file a stringa - Risultato non implementa un metodo in ambito denominato `read_to_string`

use std::env; 
use std::io::BufRead; 
use std::fs::File; 
use std::path::Path; 

fn main() { 
    let args: Vec<_> = env::args().collect(); 
    let pattern = &args[1]; 

    if let Some(a) = env::args().nth(2) { 
     let path = Path::new(&a); 
     let mut file = File::open(&path); 
     let mut s = String::new(); 
     file.read_to_string(&mut s); 
     println!("{:?}", s); 
    } else { 
     //do something 
    } 
} 

Tuttavia, ho ricevuto un messaggio come questo:

error: no method named `read_to_string` found for type `std::result::Result<std::fs::File, std::io::Error>` in the current scope 
    --> src/main.rs:14:14 
    | 
14 |   file.read_to_string(&mut s); 
    |    ^^^^^^^^^^^^^^ 

Cosa sto sbagliando? sguardo

risposta

13

Let al vostro messaggio di errore:

error: no method named `read_to_string` found for type `std::result::Result<std::fs::File, std::io::Error>` in the current scope 
    --> src/main.rs:14:14 
    | 
14 |   file.read_to_string(&mut s); 
    |    ^^^^^^^^^^^^^^ 

Il messaggio di errore è più o meno quello che dice sulla latta - il tipo Result fa non hanno il metodo read_to_string. Questo è in realtà a method on the trait Read.

Hai un Result perché File::open(&path)può non. Il guasto è rappresentato con il tipo Result. La prima parte di Result è Ok, che rappresenta il caso di successo. L'altra parte è Err, che è il caso di errore.

È necessario gestire il caso di errore in qualche modo. Il più facile è a morire solo in caso di errore, utilizzando expect:

let mut file = File::open(&path).expect("Unable to open"); 

avrete anche bisogno di portare Read in ambito di avere accesso a read_to_string:

use std::io::Read; 

avevo consiglio vivamente la lettura attraverso The Rust Programming Language e lavorando gli esempi. Penso che questi documenti siano di prim'ordine!

+1

https://doc.rust-lang.org/std/fs/struct.File.html: qui dice che File ha un metodo read_to_string. Perché non posso accedervi qui, come ha fatto il primo codice di esempio? – user3918985

+1

@ user3918985 'File' implementa' Leggi', che fornisce 'read_to_string'. Non intendo ciò che intendi con "qui". Devi 'usare' quel tratto (come mostro) per avere questi metodi in ambito. – Shepmaster

+0

Grazie per la tua esaustiva spiegazione. – liuyanghejerry

Problemi correlati