如何推断函数的返回类型?

时间:2017-11-17 10:02:31

标签: rust type-inference

推断出块的返回类型。

fn main() {
    let x = { 5 };
    println!("{}", x);
}

但是当我给这个块命名时,我必须指定一个类型。

fn five() -> i32 {
    5
}

fn main() {
    let x = five();
    println!("{}", x);
}

如何避免选择类型?

1 个答案:

答案 0 :(得分:5)

你做不到。生锈explicitly prohibits this by design

但是,对于大型和复杂的返回类型,您有以下选项:

  • 使用闭包 - 因为它是本地的,允许推断其类型
  • 返回盒装类型
  • 返回an abstract type

您可以在What is the correct way to return an Iterator (or any other trait)?

的答案中看到这些实例
相关问题