我正在建模一个API,其中方法重载将是一个很好的选择.我天真的尝试失败了:
// fn attempt_1(_x: i32) {}
// fn attempt_1(_x: f32) {}
// Error: duplicate definition of value `attempt_1`
Run Code Online (Sandbox Code Playgroud)
然后我添加了一个枚举并完成了:
enum IntOrFloat {
Int(i32),
Float(f32),
}
fn attempt_2(_x: IntOrFloat) {}
fn main() {
let i: i32 = 1;
let f: f32 = 3.0;
// Can't pass the value directly
// attempt_2(i);
// attempt_2(f);
// Error: mismatched types: expected enum `IntOrFloat`
attempt_2(IntOrFloat::Int(i));
attempt_2(IntOrFloat::Float(f));
// Ugly that the caller has to explicitly wrap the parameter
}
Run Code Online (Sandbox Code Playgroud)
rust-ini有一个功能:
pub fn section<'a, S>(&'a self, name: Option<S>) -> Option<&'a Properties>
where S: Into<String>
Run Code Online (Sandbox Code Playgroud)
我想读一个没有节的文件,所以我这样称呼它:
let ifo_cfg = match Ini::load_from_file("conf.ini") {
Result::Ok(cfg) => cfg,
Result::Err(err) => return Result::Err(err.msg),
};
let section = ifo_cfg.section(None).unwrap();
Run Code Online (Sandbox Code Playgroud)
但它给出了编译错误:
无法推断出足够的类型信息
_; 需要输入注释或通用参数绑定[E0282]
我可以像这样解决它:
let none: Option<String> = None;
let section = ifo_cfg.section(none).unwrap();
Run Code Online (Sandbox Code Playgroud)
如何在没有附加线的情况下解决这个问题none?