Skip to content

Support for inferred return types (_) in function signatures #3682

Open
@hagz0r

Description

@hagz0r

Short Description:

Add the ability to use the underscore character (_) (or similar) to indicate the return type in function signatures in Rust.

This would allow the compiler to automatically determine the type of the return value based on the function body, simplifying syntax in cases where the type is obvious from context.

Motivation:

Currently in Rust, when writing functions, you must explicitly specify the return type in the signature. In many cases, the type of the return value is obvious from context, and having to explicitly specify it adds unnecessary verbosity. Supporting automatic output of the return type will:

  • Simplify function signatures.
  • Reduce the probability of errors related to incorrect return type specification.
  • Increase code readability by focusing on the logic of the function rather than its types.

Examples:

fn add(x: i32, y: i32) -> _ {
    x + y
}


// In this case, the compiler will automatically determine that the returned type is `i32`.
fn concatenate(s1: &str, s2: &str) -> _  {
    format!({}{}, s1, s2)
}
// Here the compiler will output the type `String`.

С++ References

auto add(int x, int y) {
    return x + y;
}
// int

auto concatenate(const std::string& s1, const std::string& s2) {
    return s1 + s2;
}
// std::string.

Unresolved issues:

Should this function be limited to certain types of functions (for example, functions with a single return statement)?

How will this function interact with the existing type inference mechanisms in Rust, especially in more complex cases involving universal functions or multiple returned data?

Future opportunities:
Extending the idea of type inference to other parts of the function signature, such as parameter types, where appropriate.

Conclusion:

The ability to automatically determine the type of the return value in function signatures will provide more convenient and readable encoding, especially in simple cases when the type of the return value is obvious from the context. However, care should be taken to ensure that this function does not introduce unnecessary ambiguity and does not complicate debugging.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-langRelevant to the language team, which will review and decide on the RFC.T-typesRelevant to the types team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions