umma.dev

Rust

Here are some code snippets taken from the Rust docs!

What is Rust?

A statically and strongly typed systems programming language.

Getting Started

curl https://sh.rustup.rs -sSf | sh
rustup component add rust-docs

Basics

// hello.rs

fn main() {
  println("Hello World!");
}
rustc hello.rs
./hello
Hello World!

Loops

fn main() {
  for i in 0...5 {
    if i % 2 == 0 {
      println!("even {}", i);
    } else {
      println!("odd {}", i);
    }
  }
}

Functions

fn sqr(x: f64) -> f64 {
  return x * x;
}

fn main() {
  let res = sqr(2.0);
  println!("square is {}", res);
}
fn factorial(n: u64) -> u64 {
  if n == 0 {
    1
  } else {
    n * factorial(n-1);
  }
}

Arrays

fn main() {
  let arr = [10, 20, 30, 40];
  let first = arr[0];
  println!("first {}", first);

  for i in 0..4 {
    println!("[{}] = {}", i,arr[i]);
  }
  println!("length{}", arr.len());
}

Output:

first 10
[0] = 10
[1] = 20
[2] = 30
[3] = 40
length 4
fn sum(values: &[i32] -> i32) {
  let mut res = 0;
  for i in 0..values.len() {
    res += values[i]
  }
  res
}

fn main() {
  let arr = [10, 20, 30, 40];
  let res = sum(&arr);
  println!("sum{}", res)
}

Iterators

fn main() {
  let mut iter = 0..3;
  assert_eq!(iter.next(), Some(0));
  assert_eq!(iter.next(), Some(1));
  assert_eq!(iter.next(), Some(2));
  assert_eq!(iter.next(), None);
}
fn main() {
  let arr = [10, 20, 30];
  for i in arr.iter() {
    println!("{}", i);
  }
  let slice = &arr;
  for i in slice {
    println!("{}", i);
  }
}
fn main() {
  let sum: i32 = (0..5).sum();
  println!("sum was {}", sum);

  let sum: i64 = [10, 20, 30].iter().sum();
  println!("sum was {}", sum);
}

Getting Command Line Arguments

fn main() {
  for arg in std::env::args() {
    println!("'{}'", arg);
  }
}

Output:

src$ rust c args0.rs
src% ./args0 42 'hello dolly' frodo
'./args0'
'42'
'hello dolly'
'frodo'

Matching

let text = match n {
  0 => "zero",
  1 => "one",
  2 => "two",
  _ => "many",
};

Reading From Files

use std::env;
use std::fs::File;
use std::io::Read;

fn main() {
  let first = env::args().nth(1).expect("please supply a filename");

  let mut file = File::open(&first).expect("can't open the file");

  let mut text = String::new();
  file.read_to_string(&mut text).expect("can't read the file");

  println!("file had {} bytes", text.len());
}
fn read_to_string(filename: &str) -> io::Result<String> {
  let mut file = try!(File::open(&filename));
  let mut text = String::new();
  try!(file.read_to_string(&mut text));
  Ok(text)
}