Ad space (banner)
Lesson 7 / 20

Writing your own function

This lesson covers the basic form for defining a function in Rust.

A function is defined as fn name(arg: type) -> return_type { ... }. If the last line of the function is written without a semicolon, it automatically becomes the return value.

The sample code defines fn greet(name: &str) -> String, which takes a name and builds a greeting with the format! macro.

A common early stumble is deciding whether to write return and whether to put a semicolon on the final expression. Leaving the semicolon off makes that value the return value; adding it means the function returns nothing (the () type).

In professional work, getting comfortable with this expression-oriented style is what lets you write concise, idiomatic Rust.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Rust directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)