From fd603cd2634c59bd7286a8c962279c97e3374075 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Thu, 15 Jan 2015 14:47:21 -0500 Subject: [PATCH] Clarify function return style. Suggested here: http://stackoverflow.com/a/27962076/24817 --- src/doc/trpl/functions.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/doc/trpl/functions.md b/src/doc/trpl/functions.md index 6980663651a..eae7fc19895 100644 --- a/src/doc/trpl/functions.md +++ b/src/doc/trpl/functions.md @@ -142,5 +142,23 @@ fn foo(x: i32) -> i32 { } ``` +The previous definition without `return` may look a bit strange if you haven't +worked in an expression-based language before, but it becomes intutive over +time. If this were production code, we wouldn't write it in that way anyway, +we'd write this: + +```rust +fn foo(x: i32) -> i32 { + if x < 5 { + x + } else { + x + 1 + } +} +``` + +Because `if` is an expression, and it's the only expression in this function, +the value will be the result of the `if`. + There are some additional ways to define functions, but they involve features that we haven't learned about yet, so let's just leave it at that for now.