0

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.

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.