Rust (programming language): Difference between revisions

From David's Wiki
(Created page with "Rust is a low-level programming language. It's main advantage is supposed to be memory safety by default. Recently, Rust has been adopted to many systems applications such a...")
 
No edit summary
Line 9: Line 9:
</pre>
</pre>


==Syntax==
===Example===
<syntaxhighlight lang="rust">
# Const variable, must have type annotation.
const IMPORTANT_VALUE: i32 = 50;
fn main() {
  # C++: int x = 3;
  let mut x: i32 = 3;
  # Shadowing, creating a new variable.
  let x = x + 5;
 
  # Loop over values [0, 1, 2]
  for i in 0..3 {
    println!("This number is {}", i);
  }
 
  # Ternary is a single line if statement.
  let big_x = if x > 5 {x} else {5};
}
fn lerp(a: f64, b: f64, x: f64) -> f64 {
  # No semicolon implies return.
  (1.0 - x) * a + x * b
}
# Copied from rustlings.
pub fn fizz_if_foo(fizzish: &str) -> &str {
    if fizzish == "fizz" {
        "foo"
    } else if fizzish == "fuzz" {
        "bar"
    } else {
        "baz"
    }
}
</syntaxhighlight>


==Resources==
==Resources==
* [https://github.com/rust-lang/rustlings/ Rustlings] - some rust exercises.
* [https://github.com/rust-lang/rustlings/ Rustlings] - some rust exercises.
* [https://doc.rust-lang.org/book/print.html The Rust Programming Language]
* [https://doc.rust-lang.org/stable/rust-by-example/index.html Rust by example book]

Revision as of 04:57, 23 June 2021

Rust is a low-level programming language. It's main advantage is supposed to be memory safety by default.
Recently, Rust has been adopted to many systems applications such as the Linux kernel drivers and Android.

Usage

Installation

See Install

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Syntax

Example

# Const variable, must have type annotation.
const IMPORTANT_VALUE: i32 = 50;
fn main() {
  # C++: int x = 3;
  let mut x: i32 = 3;

  # Shadowing, creating a new variable.
  let x = x + 5;
<br />
  # Loop over values [0, 1, 2]
  for i in 0..3 {
    println!("This number is {}", i);
  }
<br />
  # Ternary is a single line if statement.
  let big_x = if x > 5 {x} else {5};
}

fn lerp(a: f64, b: f64, x: f64) -> f64 {
   # No semicolon implies return.
  (1.0 - x) * a + x * b
}

# Copied from rustlings.
pub fn fizz_if_foo(fizzish: &str) -> &str {
    if fizzish == "fizz" {
        "foo"
    } else if fizzish == "fuzz" {
        "bar"
    } else {
        "baz"
    }
}

Resources