相关疑难解决方法(0)

我如何近似方法重载?

我正在建模一个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)

做了一些快速搜索,我发现了 一些 关于重载的引用,所有这些引用 …

overloading rust

8
推荐指数
3
解决办法
931
查看次数

将None传递给接受Option的函数

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

rust

2
推荐指数
1
解决办法
458
查看次数

标签 统计

rust ×2

overloading ×1