Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 620
ceving Avatar asked Nov 17 '17 10:11

ceving


People also ask

How do you determine the return type of a function?

I can obtain the type of the function by using typeof : type t = typeof test; Here, t will be () => number .

What is the meaning of the return type of this function?

The result of a function is called its return value and the data type of the return value is called the return type. Every function declaration and definition must specify a return type, whether or not it actually returns a value.

How do you get the return type of a method in TypeScript?

Use the ReturnType utility type to get the return type of a function in TypeScript, e.g. type T = ReturnType<typeof myFunction> . The ReturnType utility type constructs a type that consists of the return type of the provided function type.


1 Answers

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)?

like image 187
Jan Hohenheim Avatar answered Sep 27 '22 19:09

Jan Hohenheim