November 2017
Intermediate to advanced
264 pages
5h 45m
English
In the same way as we did for reading a file, we could also use the try! macro when writing to a file, like here:
// code from Chapter 11/code/write_file_try.rs:
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::error::Error;
use std::io;
struct Info {
name: String,
age: i32,
rating: i32
}
impl Info {
fn as_bytes(&self) -> &[u8] {
self.name.as_bytes()
}
fn format(&self) -> String {
format!("{};{};{}\n", self.name, self.age, self.rating)
}
}
fn main() {
let path = Path::new("info.txt");
let display = path.display();
let file = match write_file(&path) {
Err(why) => panic!("couldn't write info to file {}: {}",
display,
Error::description(&why)),
Ok(file) => file,
};
}
fn write_file(path: &Path) ...Read now
Unlock full access