Designed to write fast, correct code for large scale maintable systems and embeddable into other languages
Safety and control
Safe by design, can't have seg fault, null ptrs, and dangling ptrs, or parallel dat race
Enums with match, structs, tuples, options, traits that can be implemented or put in generics
Default immutable and no shared memory, its all opt in with mut and unsafe blocks for everything not allowed
Rust can talk to C, basically directly with ft calls
fnmain() {println!("Hello World!");}
rustchello.rs./hello
Basics Variables and Types?
rust infers types
//Can specify types, but optionallet x:i32=42; //i32 good for everything, long in C, int in Java, and dfaultlet b:f64=3.14; // 64-bit floatlet c:bool=true; let d:char='z'; let e:&str="Hello"; // String sliceletmut s =String::from("hello"); //String object that is mutables.push_str(", world!");let pair: (char, i32) = ('a', 17)pair.0; //apair.1//17let (_, r) = slice.split_at(middle)
Lists
letmut numbers:Vec<i32> =Vec::new();numbers.push(1);numbers.push(2);numbers.push(3);let first = numbers[0]; // Access elementlet length = numbers.len(); // Get lengthlet x =vec![1,2,3,4,5,6,7,8].iter().map(|x| x +3).fold(0, |x,y| x + y);
Control
// Looploop {println!("This will loop forever");break; // Exit the loop}// While loopwhile x <5 {println!("x is {}", x); x +=1;}whileletSome(value) = some_option.take() {// Process value}// For loopfor i in0..5 {println!("i is {}", i);}match some_value {1=>println!("One"),2=>println!("Two"), _ =>println!("Something else"),}//let elselet PATTERN = EXPRESSION else {// Diverging code block};letOk(count) =u64::from_str(count_str) else {panic!("Can't parse integer");}; //count set
let s =String::from("hello");takes_ownership(s); // s is moved here and then droppedlet x =5;let y =&x; // y is a reference to xletmut z =5;let r =&mut z; // r is mutable reference to z*r +=1;
Concurrency
Threads can communiate by channel
use std::thread;use std::time::Duration;fnmain() {let handle = thread::spawn(|| {println!("Hello from spawn"); }); handle.join().unwrap(); thread::sleep(Duration::from_secs(2));println!("Main thread ends");}
Modules and Crates
mod utils {pubfngreet(name:&str) ->String {format!("Hello, {}!", name) }}fnmain() {let name ="Alice";let greeting = utils::greet(name);println!("{}", greeting);}