Skip to content

Instantly share code, notes, and snippets.

@tgotwig
Last active September 29, 2021 20:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgotwig/a9e46acc4d24c8ffc0def138f0ac496d to your computer and use it in GitHub Desktop.
Save tgotwig/a9e46acc4d24c8ffc0def138f0ac496d to your computer and use it in GitHub Desktop.
๐Ÿฆ€ Rust Introduction

Rust Introduction

  • A nice alternative to C++
  • Compiles to native programs ๐Ÿš€
  • Has the very nice package manager Cargo

Expecience

Motivation

Naming differences

โ˜•๏ธ Java ๐Ÿฆ€ Rust
Maven Cargo
Checkstyle Clippy
class impl
List Vec
interface struct / trait
Lambda Closure
switch case match

Objects

Rust has no new keyword, you have to have a function which is called new inside of an impl thing:

  • struct Sheep {/* bunch of field signatures */} // basically an interface for fields
  • trait Animal {/* bunch of method signatures */} // basically an interface for methods, can also contain implementations
  • impl Sheep {/* bunch of methods with the fields from struct */} // from that you can create an object:
    • Sheep::new("Dolly"); // would need implementation for new
  • impl Animal for Sheep {/* implemented methods from Animal */} // Implements Animal trait for Sheep:
    • let mut dolly: Sheep = Animal::new("Dolly");

from https://doc.rust-lang.org/rust-by-example/trait.html

Borrowing

Drops say after calling print_out/1:

fn main() {
  let say = String::from("Cat");
  print_out(say);
  println!("Again: {}", say); // ERROR
}

fn print_out(to_print: String) {
  println!("{}", to_print);
}

Returns say after calling print_out/1:

fn main() {
  let say = String::from("Cat");
  print_out(&say);
  println!("Again: {}", say);
}

fn print_out(to_print: &String) {
  println!("{}", to_print);
}

Compiler

Sometimes the compiler says what to do to fix a problem:

24 |       let format_args: &str = match matches.value_of("format") {
   |  _____________________________^
25 | |         Some(x) => x,
26 | |         None => "avchd,avi,flv,mkv,mov,mp4,webm,wmv",
27 | |     };
   | |_____^ help: replace with: `matches.value_of("format").unwrap_or("avchd,avi,flv,mkv,mov,mp4,webm,wmv")`

Learning

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment