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
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
@ 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
Grazie per la tua esaustiva spiegazione. – liuyanghejerry