How to infer the return type of a function? [duplicate]

我们两清 提交于 2020-03-21 16:09:47

问题


The return type of a block is inferred.

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

But when I give the block a name, I have to specify a type.

fn five() -> i32 {
    5
}

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

How can I avoid selecting a type?


回答1:


You cannot. Rust explicitly prohibits this by design.

However, for large and complex return types, you have the following options:

  • Use a closure instead - As it is local, it is allowed to infer its type
  • Return a boxed type
  • Return an abstract type

You can see a practical example of these in the answer for What is the correct way to return an Iterator (or any other trait)?



来源:https://stackoverflow.com/questions/47347962/how-to-infer-the-return-type-of-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!