]> git.lizzy.rs Git - rust.git/blob - src/doc/book/functions.md
Rollup merge of #31061 - brson:bib, r=steveklabnik
[rust.git] / src / doc / book / functions.md
1 % Functions
2
3 Every Rust program has at least one function, the `main` function:
4
5 ```rust
6 fn main() {
7 }
8 ```
9
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`:
14
15 ```rust
16 fn foo() {
17 }
18 ```
19
20 So, what about taking arguments? Here’s a function that prints a number:
21
22 ```rust
23 fn print_number(x: i32) {
24     println!("x is: {}", x);
25 }
26 ```
27
28 Here’s a complete program that uses `print_number`:
29
30 ```rust
31 fn main() {
32     print_number(5);
33 }
34
35 fn print_number(x: i32) {
36     println!("x is: {}", x);
37 }
38 ```
39
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.
42
43 Here’s a complete program that adds two numbers together and prints them:
44
45 ```rust
46 fn main() {
47     print_sum(5, 6);
48 }
49
50 fn print_sum(x: i32, y: i32) {
51     println!("sum is: {}", x + y);
52 }
53 ```
54
55 You separate arguments with a comma, both when you call the function, as well
56 as when you declare it.
57
58 Unlike `let`, you _must_ declare the types of function arguments. This does
59 not work:
60
61 ```rust,ignore
62 fn print_sum(x, y) {
63     println!("sum is: {}", x + y);
64 }
65 ```
66
67 You get this error:
68
69 ```text
70 expected one of `!`, `:`, or `@`, found `)`
71 fn print_number(x, y) {
72 ```
73
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.
79
80 What about returning a value? Here’s a function that adds one to an integer:
81
82 ```rust
83 fn add_one(x: i32) -> i32 {
84     x + 1
85 }
86 ```
87
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:
92
93 ```rust,ignore
94 fn add_one(x: i32) -> i32 {
95     x + 1;
96 }
97 ```
98
99 We would get an error:
100
101 ```text
102 error: not all control paths return a value
103 fn add_one(x: i32) -> i32 {
104      x + 1;
105 }
106
107 help: consider removing this semicolon:
108      x + 1;
109           ^
110 ```
111
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.
115
116 ## Expressions vs. Statements
117
118 Rust is primarily an expression-based language. There are only two kinds of
119 statements, and everything else is an expression.
120
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.
126
127 In some languages, variable bindings can be written as expressions, not
128 statements. Like Ruby:
129
130 ```ruby
131 x = y = 5
132 ```
133
134 In Rust, however, using `let` to introduce a binding is _not_ an expression. The
135 following will produce a compile-time error:
136
137 ```ignore
138 let x = (let y = 5); // expected identifier, found keyword `let`
139 ```
140
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.
143
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 [only one owner](ownership.html), and any
149 other returned value would be too surprising:
150
151 ```rust
152 let mut y = 5;
153
154 let x = (y = 6);  // x has the value `()`, not `6`
155 ```
156
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.
164
165 What is this exception that makes us say "almost"? You saw it already, in this
166 code:
167
168 ```rust
169 fn add_one(x: i32) -> i32 {
170     x + 1
171 }
172 ```
173
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.
177
178 ## Early returns
179
180 But what about early returns? Rust does have a keyword for that, `return`:
181
182 ```rust
183 fn foo(x: i32) -> i32 {
184     return x;
185
186     // we never run this code!
187     x + 1
188 }
189 ```
190
191 Using a `return` as the last line of a function works, but is considered poor
192 style:
193
194 ```rust
195 fn foo(x: i32) -> i32 {
196     return x + 1;
197 }
198 ```
199
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
202 time.
203
204 ## Diverging functions
205
206 Rust has some special syntax for ‘diverging functions’, which are functions that
207 do not return:
208
209 ```rust
210 fn diverges() -> ! {
211     panic!("This function never returns!");
212 }
213 ```
214
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’.
219
220 If you add a main function that calls `diverges()` and run it, you’ll get
221 some output that looks like this:
222
223 ```text
224 thread ‘<main>’ panicked at ‘This function never returns!’, hello.rs:2
225 ```
226
227 If you want more information, you can get a backtrace by setting the
228 `RUST_BACKTRACE` environment variable:
229
230 ```text
231 $ RUST_BACKTRACE=1 ./diverges
232 thread '<main>' panicked at 'This function never returns!', hello.rs:2
233 stack backtrace:
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>
246   13:                0x0 - <unknown>
247 ```
248
249 `RUST_BACKTRACE` also works with Cargo’s `run` command:
250
251 ```text
252 $ RUST_BACKTRACE=1 cargo run
253      Running `target/debug/diverges`
254 thread '<main>' panicked at 'This function never returns!', hello.rs:2
255 stack backtrace:
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>
268   13:                0x0 - <unknown>
269 ```
270
271 A diverging function can be used as any type:
272
273 ```should_panic
274 # fn diverges() -> ! {
275 #    panic!("This function never returns!");
276 # }
277 let x: i32 = diverges();
278 let x: String = diverges();
279 ```
280
281 ## Function pointers
282
283 We can also create variable bindings which point to functions:
284
285 ```rust
286 let f: fn(i32) -> i32;
287 ```
288
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:
291
292 ```rust
293 fn plus_one(i: i32) -> i32 {
294     i + 1
295 }
296
297 // without type inference
298 let f: fn(i32) -> i32 = plus_one;
299
300 // with type inference
301 let f = plus_one;
302 ```
303
304 We can then use `f` to call the function:
305
306 ```rust
307 # fn plus_one(i: i32) -> i32 { i + 1 }
308 # let f = plus_one;
309 let six = f(5);
310 ```