Russell Myers
Russell Myers

Reputation: 2017

Rust function requires return keyword. Why?

I've been playing with Rust a bit, and I'm experimenting with eliminating return statements that aren't necessary. In one case, I feel as though a return statement shouldn't be required here, but I'm getting complaints that "the body has no tail". It seems like it should with the following code:

use sqlite;
use sqlite::Connection

fn main() {
    let connection = connect();

    query(connection);
}

// The offending function
fn connect() -> Connection {
    // Simple example, shouldn't use unwrap
    sqlite::open(":memory:").unwrap();
}

I can add a return statement to the offending function like the following:

fn connect() -> Connection {
    return sqlite::open(":memory:").unwrap();
}

But I'm curious why this doesn't work.

Upvotes: 0

Views: 517

Answers (1)

Russell Myers
Russell Myers

Reputation: 2017

fn connect() -> Connection {
    sqlite::open(":memory:").unwrap()
}

Removing the semi-colon, changes the line from a statement to an expression, which has a return value, which Rust can then infer as a return value for the function.

This is covered at the very end Chapter 3 of the Rust language book as a specific example.

Upvotes: 3

Related Questions