I'm writing a file parser that parses ".toml" files (using the toml-rs crate) into Rust data types. Right now my function accepts PathBuf
for the file path. I want to make it generic so that it can accept any type of source that contains TOML:
- File paths,
PathBuf
orPath
. - String that has toml data in it.
Is it possible to achieve this?
CodePudding user response:
There's not going to be a good generic trait that's implement by both String and PathBuf they are too different. One is the content and one is a path to the content.
You could have two entry point functions one accepting a path/buf and one accepting a string (that then call the same helper)
pub fn parse_from_file<P: AsRef<Path>>(path: P) -> Toml {
let content = std::fs::read_to_string(path);
parse(content)
}
pub fn parse(content: String) -> Toml {
todo!();
}
Or you could use an enum like this:
enum ParseContent {
PathBuf(PathBuf),
Path(Path),
Content(String)
}
pub fn parse(source: ParseContent) -> Toml { todo!() }
I prefer the first.