Rust is statically typed, ahead-of-time compiled language.

Rust has a strong, static type system. However, it also has type inference.

Rust developers are called Rustaceans.

Code example:

use std::io;
 
fn main() {
    println!("Guess the number!");
 
    println!("Please input your guess.");
 
    let mut guess = String::new();
 
    io::stdin()
        .read_line(&mut guess)
        .expect("Failed to read line");
 
    println!("You guessed: {guess}");
}

main fn

main() function is a starting point for any Rust program.

To define a function:

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

The main function is special because it’s the entry and exit point of executable programs, and there are restrictions on what its return type can be for the programs to behave as expected.

Other than () the main can also return a Result<(), E>.

use std::error::Error;
use std::fs::File;
 
fn main() -> Result<(), Box<dyn Error>> {
    let greeting_file = File::open("hello.txt")?;
 
    Ok(())
}

For now, you can read Box<dyn Error> to mean “any kind of error.”

The main function may return any types that implement the std::process::Termination trait, which contains a function report that returns an ExitCode.


Rust style is to indent with four spaces, not a tab.

println! - calls a Rust macro.

Most lines of Rust code end with a semicolon.

To compile a program and output a binary:

rustc main.rs
# that will create `main` binary file in the same directory
# and can be executed with
./main

By default, Rust has a set of items defined in the standard library that it brings into the scope of every program. This set is called the prelude, and you can see everything in it in the standard library documentation. If a type you want to use isn’t in the prelude, you have to bring that type into scope explicitly with a use statement.

The :: syntax in the let mut guess = String::new(); line indicates that new is an associated function of the String type. An associated function is a function that’s implemented on a type, in this case String. This new function creates a new, empty string.

References are immutable by default. Hence, you need to write &mut guess rather than &guess to make it mutable

Result is an enumeration, often called an enum, which is a type that can be in one of multiple possible states. We call each possible state a variant.

Variables

Data types


Rust is an expression-based language.

fn main() {
    let y = {
        let x = 3;
        x + 1 // does not have a semicolon
    };
	// y == 4
}

Expressions do not include ending semicolons. If you add a semicolon to the end of an expression, you turn it into a statement, and it will then not return a value.

Comments

// this is a comment
 
/// this is a doc comment
fn plus_one(x: i32) -> i32 {
    x + 1
}

References