rust之简单⽂件读取完整版
前段时间⼀直在思考虽然之前发布的配置⽂件读取库可以使⽤,但总感觉可拓展性太差了,万⼀哪天我需要读取json配置呢!所以绞尽脑汁想到了⼀个不算完美的解决⽅案,该⽅案是实现n版后的简洁版,直接上代码:
先定义通⽤⽂件读取以及⽂件访问接⼝
// ⽂件读取统⼀接⼝
pub trait ConfReadImpl {阚清子张睿
// path: ⽂件路径
fn read_conf(&mut self, path: &str) -> Result<i32, Error>;
}
// 获取读取后的值
pub trait GetConfImpl {
fn get_string(&self, key: &str) -> String;
fn def_get_i32(&self, key: &str, def: i32) -> i32;
一老一小fn def_get_u32(&self, key: &str, def: u32) -> u32;
fn def_get_f32(&self, key: &str, def: f32) -> f32;
fn def_get_f64(&self, key: &str, def: f64) -> f64;
fn def_get_bool(&self, key: &str, def: bool) -> bool;
fn get_i32(&self, key: &str) -> i32;
fn get_u32(&self, key: &str) -> u32;
fn get_f32(&self, key: &str) -> f32;
fn get_f64(&self, key: &str) -> f64;
fn get_bool(&self, key: &str) -> bool;
}
定义统⼀调⽤⽂件⽅式
// 定义统⼀对外访问接⼝
pub trait ConfImpl: GetConfImpl + ConfReadImpl{}
// 给实现了GetConfImpl 和ConfReadImpl 的类型默认实现ConfImpl impl <T> ConfImpl for T  where T: GetConfImpl + ConfReadImpl {}
pub struct Conf {
conf_map: HashMap<String, Box<dyn ConfImpl>>,
}
impl Conf {
pub fn new () -> Self {
Self {
conf_map: HashMap::new(),
}
}
}
impl Conf {
星期一的英语单词// 初始化配置
七月英文缩写pub fn init(&mut self, key: &str, path: &str) -> &Box<dyn ConfImpl> {        ad_conf(key, path);
(key).unwrap();
}
// 初始化配置 - 读取配置⽂件
fn read_conf(&mut self, key: &str, path: &str) {
/
/ 防⽌多次调⽤
f_map.is_empty() {
} else {
return;电脑没有小喇叭
}
if !ains_key(key) {
panic!("不存在指定的功能模块");
}
let conf = _mut(key).unwrap();
// 读取⽂件读取配置文件失败
let new_conf = conf.as_mut();
if let Err(e) = ad_conf(path) {
panic!(e);
}
}
// 注册配置⽂件读取器 - 这⼀步是⼿动的
fn register_conf(&mut self) {
}
main.rs 调⽤
fn main() {
let mut conf = Conf::new();
let new_conf = conf.init("ini", "f");
println!("{}", _string("server::test"));
println!("{}", _string("my_str"));
}
到此全部完成,更多详情可下载源码查看