Expand description
This crate provides the trait FromFile that can be implemented or derived
for any struct or enum. Upon doing so, you’ll get a from_file
method
that allows you to skip having read the file the disk & choosing the correct
serde method - that will be done based on the file extension.
Quick Preview
All examples require that serde Deserialize is also derived. (see below for copy/paste example)
#[derive(Deserialize)]
struct Person {
name: String
}
impl FromFile for Person {}
fn main() {
let path = "test/fixtures/person.json";
let person = Person::from_file(path).expect("deserialize from file");
assert_eq!(person.name, String::from("Shane"));
}
Quick Preview with from_file_derive
This requires the additional crate from_file_derive
#[derive(Deserialize, FromFile)]
struct Person {
name: String
}
fn main() {
let path = "test/fixtures/person.json";
let person = Person::from_file(path).expect("deserialize from file");
assert_eq!(person.name, String::from("Shane"));
}
Copy/Paste example
#[macro_use]
extern crate serde_derive;
extern crate serde;
#[macro_use]
extern crate from_file_derive;
use from_file::FromFile;
#[derive(Deserialize, FromFile)]
struct Person {
name: String
}
fn main() {
let path = "test/fixtures/person.json";
let person = Person::from_file(path).expect("deserialize from file");
assert_eq!(person.name, String::from("Shane"));
}
Full example with imports and error handing
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate from_file_derive;
extern crate from_file;
use from_file::FromFile;
#[derive(Deserialize, FromFile, Debug, PartialEq)]
struct Person {
name: String,
age: usize
}
fn main() {
match Person::from_file("test/fixtures/person.json") {
Ok(p) => println!("Got a Person from a file!"),
Err(e) => eprintln!("{}", e)
}
}
Enums
Traits
Implement this trait to enable your Struct’s to be deserialized
from a file-path like