如何推断函数的返回类型? [重复]

问题描述 投票:4回答:1

这个问题在这里已有答案:

推断出块的返回类型。

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

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

fn five() -> i32 {
    5
}

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

如何避免选择类型?

rust type-inference
1个回答
5
投票

你不能。 Rust explicitly prohibits this by design

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

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

你可以在What is the correct way to return an Iterator (or any other trait)?的答案中看到这些实例

© www.soinside.com 2019 - 2024. All rights reserved.