Learning Rust
gitbook
gitbook
  • Introduction
  • Basics
    • Why Rust
    • Installation
    • Hello World
    • Cargo,crates and basic project structure
    • Comments and documenting the code
    • Variable bindings, constants and statics
    • Functions
    • Primitive data types
    • Operators
    • Control flows
  • Beyond The Basics
    • Vectors
    • Structs
    • Enums
    • Generics
    • Impls and traits
  • The Tough Part
    • Ownership
    • Borrowing
    • Lifetimes
  • Lets Get It Started
    • Code organization
    • Functions
    • Modules
    • Crates
    • Workspaces
    • use
    • std, primitives and preludes
Powered by GitBook
On this page
  • Hello world
  • Passing arguments
  • Returning Values
  1. Basics

Functions

  • Functions are declared with the keyword fn

  • When using arguments, you must declare data types.

  • By default functions return empty tuple (). If you want to return a value, return type must be specified after ->

Hello world

fn main() {
    println!("Hello, world!");
}

Passing arguments

fn print_sum(a: i8, b: i8) {
    println!("sum is: {}", a + b);
}

Returning Values

fn plus_one(a: i32) -> i32 {
    a + 1 //no ; means an expression, return a+1
}

fn plus_two(a: i32) -> i32 {
    return a + 2; //return a+2 but bad practice,
    //should use only on conditional returnes, except it's last expression
}

// ⭐️ Function pointers, Usage as a Data Type
let b = plus_one;
let c = b(5); //6

let b: fn(i32) -> i32 = plus_one; //same, with type inference
let c = b(5); //6
PreviousVariable bindings, constants and staticsNextPrimitive data types

Last updated 7 years ago