DEV Community

Cover image for [Rust Guide] 3.4. Functions and Comments
SomeB1oody
SomeB1oody

Posted on

[Rust Guide] 3.4. Functions and Comments

3.4.0. Before the Main Content

Welcome to Chapter 3 of Rust self-study. There are 6 sections in total:

  • Variables and Mutability
  • Data Types: Scalar Types
  • Data Types: Compound Types
  • Functions and Comments (this article)
  • Control Flow: if else
  • Control Flow: Loops

Through the small game in Chapter 2 (strongly recommended for beginners who haven't read it), you should already understand the basic syntax of Rust. In Chapter 3, we will go deeper and learn general programming concepts in Rust.

If you like it, remember to like, bookmark, and follow. Follow the series if you want to keep learning.


3.4.1. Basic Understanding of Functions

  • Functions are declared using the keyword fn
  • By convention, function and variable names follow snake_case:
    • All letters are lowercase, and words are separated by underscores
    • Example: another_function
  • Rust does not require functions to be defined before they are called, as long as they are declared and can be found. This is more flexible than some older languages (C/C++). Below is an example where the function is defined after it is called, yet still works:
fn main(){
    println!("Hello World");
    another_function();
}

fn another_function(){
    println!("Another Function");
}
Enter fullscreen mode Exit fullscreen mode

3.4.2. Function Parameters

Function parameters involve two terms: parameter and argument.

  • Parameter: A placeholder declared in a function definition to receive input values. It provides a general way for the function to process external data without depending on specific values.
  • Argument: The actual value passed into the function when it is called. It provides concrete data for the function logic.
fn main() {
    greet("Alice");
}

fn greet(name: &str) {
    println!("Hello, {}!", name);
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • "Alice" in the main function is the argument, the actual value passed to the function.
  • name in greet is the parameter, representing an input of type &str.

In the function signature, each parameter must have an explicit type, so the compiler does not need to infer it. In this case, &str is the type of name.

A function can have multiple parameters, separated by commas.


3.4.3. Statements and Expressions in Function Bodies

  • A function body consists of a series of statements and may optionally end with an expression.
  • Rust is an expression-based language. Many of its concepts are similar to Scala, as both are centered around expressions.
  • Statements perform actions.
  • Expressions evaluate to a value. An expression itself is a value.
  • Function definitions are also statements.
  • Statements do not return values, so you cannot assign a statement to a variable using let.
fn main(){
    let x = (let y = 6);// Error: expected expression, found statement (`let`)
}
Enter fullscreen mode Exit fullscreen mode

In this example, the compiler expects an expression on the right-hand side but finds a statement instead, causing an error.

fn main(){
    let y = {
        let x = 1;
        x + 3
    };
    println!("The value of y is:{}", y);
}
Enter fullscreen mode Exit fullscreen mode

Here, the block {} after let y = is an expression. Inside the block:

  • x is defined as 1
  • x + 3 computes a value

Since x + 3 is the last expression in the block, its value (4) becomes the return value of the block and is assigned to y.

If a semicolon ; is added after x + 3, it becomes a statement instead of an expression. Since statements do not return values, the block returns () (unit type).

In Rust, () is a special type whose only value is itself. If y becomes type (), it no longer stores a computed value. Also, () cannot be directly printed using println!, and attempting to do so will result in a compilation error.


3.4.4. Function Return Values

  • The return type is declared after ->, but it cannot be named.
  • In Rust, the return value is the value of the last expression in the function body.
  • To return early, use the return keyword with a value.
fn machine() -> u32 {
    6657
}

fn main(){
    let wjq = machine();
    println!("The value of wjq is:{}", wjq);
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • The return type of machine is u32
  • The function body contains a single expression 6657
  • Since it is the last expression and has no semicolon, it becomes the return value

3.4.5 Comments

  • Single-line comments use //
  • Multi-line comments use /* */

Example:

fn machine() -> u32 {
    6657
}

/* let's go g2
let's go spirit
let's go navi
*/

fn main(){
    let wjq = machine();// 6657 up up!
    println!("The value of wjq is:{}", wjq);
}
Enter fullscreen mode Exit fullscreen mode

Rust also has documentation comments, which will be discussed separately later.

Top comments (0)