3 Every Rust program has at least one function, the `main` function:
10 This is the simplest possible function declaration. As we mentioned before,
11 `fn` says ‘this is a function’, followed by the name, some parentheses because
12 this function takes no arguments, and then some curly braces to indicate the
13 body. Here’s a function named `foo`:
20 So, what about taking arguments? Here’s a function that prints a number:
23 fn print_number(x: i32) {
24 println!("x is: {}", x);
28 Here’s a complete program that uses `print_number`:
35 fn print_number(x: i32) {
36 println!("x is: {}", x);
40 As you can see, function arguments work very similar to `let` declarations:
41 you add a type to the argument name, after a colon.
43 Here’s a complete program that adds two numbers together and prints them:
50 fn print_sum(x: i32, y: i32) {
51 println!("sum is: {}", x + y);
55 You separate arguments with a comma, both when you call the function, as well
56 as when you declare it.
58 Unlike `let`, you _must_ declare the types of function arguments. This does
63 println!("sum is: {}", x + y);
70 expected one of `!`, `:`, or `@`, found `)`
71 fn print_number(x, y) {
74 This is a deliberate design decision. While full-program inference is possible,
75 languages which have it, like Haskell, often suggest that documenting your
76 types explicitly is a best-practice. We agree that forcing functions to declare
77 types while allowing for inference inside of function bodies is a wonderful
78 sweet spot between full inference and no inference.
80 What about returning a value? Here’s a function that adds one to an integer:
83 fn add_one(x: i32) -> i32 {
88 Rust functions return exactly one value, and you declare the type after an
89 ‘arrow’, which is a dash (`-`) followed by a greater-than sign (`>`). The last
90 line of a function determines what it returns. You’ll note the lack of a
91 semicolon here. If we added it in:
94 fn add_one(x: i32) -> i32 {
99 We would get an error:
102 error: not all control paths return a value
103 fn add_one(x: i32) -> i32 {
107 help: consider removing this semicolon:
112 This reveals two interesting things about Rust: it is an expression-based
113 language, and semicolons are different from semicolons in other ‘curly brace
114 and semicolon’-based languages. These two things are related.
116 ## Expressions vs. Statements
118 Rust is primarily an expression-based language. There are only two kinds of
119 statements, and everything else is an expression.
121 So what's the difference? Expressions return a value, and statements do not.
122 That’s why we end up with ‘not all control paths return a value’ here: the
123 statement `x + 1;` doesn’t return a value. There are two kinds of statements in
124 Rust: ‘declaration statements’ and ‘expression statements’. Everything else is
125 an expression. Let’s talk about declaration statements first.
127 In some languages, variable bindings can be written as expressions, not just
128 statements. Like Ruby:
134 In Rust, however, using `let` to introduce a binding is _not_ an expression. The
135 following will produce a compile-time error:
138 let x = (let y = 5); // expected identifier, found keyword `let`
141 The compiler is telling us here that it was expecting to see the beginning of
142 an expression, and a `let` can only begin a statement, not an expression.
144 Note that assigning to an already-bound variable (e.g. `y = 5`) is still an
145 expression, although its value is not particularly useful. Unlike other
146 languages where an assignment evaluates to the assigned value (e.g. `5` in the
147 previous example), in Rust the value of an assignment is an empty tuple `()`
148 because the assigned value can have [just one owner](ownership.html), and any
149 other returned value would be too surprising:
154 let x = (y = 6); // x has the value `()`, not `6`
157 The second kind of statement in Rust is the *expression statement*. Its
158 purpose is to turn any expression into a statement. In practical terms, Rust's
159 grammar expects statements to follow other statements. This means that you use
160 semicolons to separate expressions from each other. This means that Rust
161 looks a lot like most other languages that require you to use semicolons
162 at the end of every line, and you will see semicolons at the end of almost
163 every line of Rust code you see.
165 What is this exception that makes us say "almost"? You saw it already, in this
169 fn add_one(x: i32) -> i32 {
174 Our function claims to return an `i32`, but with a semicolon, it would return
175 `()` instead. Rust realizes this probably isn’t what we want, and suggests
176 removing the semicolon in the error we saw before.
180 But what about early returns? Rust does have a keyword for that, `return`:
183 fn foo(x: i32) -> i32 {
186 // we never run this code!
191 Using a `return` as the last line of a function works, but is considered poor
195 fn foo(x: i32) -> i32 {
200 The previous definition without `return` may look a bit strange if you haven’t
201 worked in an expression-based language before, but it becomes intuitive over
204 ## Diverging functions
206 Rust has some special syntax for ‘diverging functions’, which are functions that
211 panic!("This function never returns!");
215 `panic!` is a macro, similar to `println!()` that we’ve already seen. Unlike
216 `println!()`, `panic!()` causes the current thread of execution to crash with
217 the given message. Because this function will cause a crash, it will never
218 return, and so it has the type ‘`!`’, which is read ‘diverges’.
220 If you add a main function that calls `diverges()` and run it, you’ll get
221 some output that looks like this:
224 thread ‘<main>’ panicked at ‘This function never returns!’, hello.rs:2
227 If you want more information, you can get a backtrace by setting the
228 `RUST_BACKTRACE` environment variable:
231 $ RUST_BACKTRACE=1 ./diverges
232 thread '<main>' panicked at 'This function never returns!', hello.rs:2
234 1: 0x7f402773a829 - sys::backtrace::write::h0942de78b6c02817K8r
235 2: 0x7f402773d7fc - panicking::on_panic::h3f23f9d0b5f4c91bu9w
236 3: 0x7f402773960e - rt::unwind::begin_unwind_inner::h2844b8c5e81e79558Bw
237 4: 0x7f4027738893 - rt::unwind::begin_unwind::h4375279447423903650
238 5: 0x7f4027738809 - diverges::h2266b4c4b850236beaa
239 6: 0x7f40277389e5 - main::h19bb1149c2f00ecfBaa
240 7: 0x7f402773f514 - rt::unwind::try::try_fn::h13186883479104382231
241 8: 0x7f402773d1d8 - __rust_try
242 9: 0x7f402773f201 - rt::lang_start::ha172a3ce74bb453aK5w
243 10: 0x7f4027738a19 - main
244 11: 0x7f402694ab44 - __libc_start_main
245 12: 0x7f40277386c8 - <unknown>
249 `RUST_BACKTRACE` also works with Cargo’s `run` command:
252 $ RUST_BACKTRACE=1 cargo run
253 Running `target/debug/diverges`
254 thread '<main>' panicked at 'This function never returns!', hello.rs:2
256 1: 0x7f402773a829 - sys::backtrace::write::h0942de78b6c02817K8r
257 2: 0x7f402773d7fc - panicking::on_panic::h3f23f9d0b5f4c91bu9w
258 3: 0x7f402773960e - rt::unwind::begin_unwind_inner::h2844b8c5e81e79558Bw
259 4: 0x7f4027738893 - rt::unwind::begin_unwind::h4375279447423903650
260 5: 0x7f4027738809 - diverges::h2266b4c4b850236beaa
261 6: 0x7f40277389e5 - main::h19bb1149c2f00ecfBaa
262 7: 0x7f402773f514 - rt::unwind::try::try_fn::h13186883479104382231
263 8: 0x7f402773d1d8 - __rust_try
264 9: 0x7f402773f201 - rt::lang_start::ha172a3ce74bb453aK5w
265 10: 0x7f4027738a19 - main
266 11: 0x7f402694ab44 - __libc_start_main
267 12: 0x7f40277386c8 - <unknown>
271 A diverging function can be used as any type:
274 # fn diverges() -> ! {
275 # panic!("This function never returns!");
277 let x: i32 = diverges();
278 let x: String = diverges();
283 We can also create variable bindings which point to functions:
286 let f: fn(i32) -> i32;
289 `f` is a variable binding which points to a function that takes an `i32` as
290 an argument and returns an `i32`. For example:
293 fn plus_one(i: i32) -> i32 {
297 // without type inference
298 let f: fn(i32) -> i32 = plus_one;
300 // with type inference
304 We can then use `f` to call the function:
307 # fn plus_one(i: i32) -> i32 { i + 1 }