Expand description
Loading values from paths.
This crate provides the FromPath trait for types that can have values loaded from paths.
There are also the load convenience function and the Load extension trait for
when the types can be inferred.
§Example
Firstly, we need to implement the FromPath trait, and then use it via load or Load:
use std::{fs::read_to_string, io::Error, path::Path};
use from_path::{load, FromPath, Load};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Content {
pub string: String,
}
impl Content {
pub fn new(string: String) -> Self {
Self { string }
}
}
impl FromPath for Content {
type Error = Error;
fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, Self::Error> {
read_to_string(path).map(Self::new)
}
}
let path = "hello-world";
let content: Content = load(path).unwrap();
assert_eq!(content.string.trim(), "Hello, world!");
let extended: Content = path.load().unwrap();
assert_eq!(content, extended);Traits§
Functions§
- load
- Loads the value of the given type from the given path.