我正在撰寫一個檔案決議器,它將“.toml”檔案(使用toml-rs crate)決議為 Rust 資料型別。現在我的函式接受PathBuf檔案路徑。我想讓它通用,以便它可以接受包含 TOML 的任何型別的源:
- 檔案路徑,
PathBuf或Path. - 包含 toml 資料的字串。
有可能實作這一目標嗎?
uj5u.com熱心網友回復:
String 和 PathBuf 都不會實作一個好的通用特征,它們太不同了。一個是內容,一個是內容的路徑。
您可以有兩個入口點函式,一個接受路徑/buf,一個接受字串(然后呼叫相同的助手)
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!();
}
或者你可以使用這樣的列舉:
enum ParseContent {
PathBuf(PathBuf),
Path(Path),
Content(String)
}
pub fn parse(source: ParseContent) -> Toml { todo!() }
我更喜歡第一個。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510458.html
標籤:仿制药锈
