Senior Engineer
Statens Kartverk
esphen_
esphen
espen.dev
And why the world needed another programming language
Source: benchmarksgame-team.pages.debian.net
fn message_passing_example() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("Got: {}", received);
}
fn mutex_example() {
let counter = Mutex::new(0);
let mut handles = vec![];
for _ in 0..10 {
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
fn main() {
let i = 1;
i = i + 5; // Compilation error
let mut j = 1;
j = j + 5; // OK!
let foo = Foo::new();
let mut k = &foo;
k.foo = "Hi" // Compilation error!
let mut l = &mut foo;
k.foo = "Hi" // Ok!
}
// Vars are always defined
// foo can at no point be null
let foo = 5
// Create Option<T> variables
// Notice type inference
let some_number = Some(5);
let some_string = Some("a string");
let absent_number: Option<i32> = None;
// Get values from Option<T>
let number1 = some_number.unwrap();
let number2 = some_number.unwrap_or(0);
let number3 = some_number.unwrap_or_default();
let number4 = some_number?;
match number {
Some(i) => println!("value: {}", i),
None => eprintln!("It was None"),
}
if let Some(s) = some_string {
println!("value: {}", s);
}
fn can_fail() -> Result<string, Error> {
// In this example case we failed
let success = false;
if success {
Ok("It worked!")
} else {
Err("Oh no!")
}
}
fn main() {
let result = can_fail();
match (result) {
Ok(value) => {
println!("The value was: {}", value);
},
Err(err) => {
panic!("It failed! Error: {}", err);
},
}
}
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("Got: {}", received);
}
// Add features from a trait to a struct
#[derive(Copy)]
struct Pancakes;
#[route(GET, "/")]
fn index() {}
// The function is only included in the
// build when compiling for macOS
#[cfg(target_os = "macos")]
fn macos_only() {}
// The function is only included in the
// build when compiling for Windows
#[cfg(target_os = "windows")]
fn win_only() {}
fn main() {
println!("Hello from the println macro");
let array = vec![1, 2, 3];
let config_cirectory = if cfg!(windows) {
win_only()
} else {
macos_only()
};
}
async fn get_from_server() -> Result<Response, Error> {
reqwest::get(
"https://www.rust-lang.org"
).await?
}
async fn main() {
// Future<Result<Response, Error>>
let future = hello_world();
let response = future.await?;
println!("The response was {}", response);
}
cargo doc --open
/// Adds a number to another number
/// ```
/// let result = add(1, 2);
///
/// assert_eq!(result, 3);
/// ```
fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
let result = crate::add(2, 2);
assert_eq!(result, 4);
}
#[test]
fn add_negative_number() {
let result = crate::add(-1, 2);
// Custom error message
assert_eq!(
result,
1,
"Adding negative numbers failed. Was: {}",
result
);
}
}
fn hold_my_vec<T>(_: Vec<T>) {}
fn main() {
let v = vec![2, 3, 5, 7, 11, 13, 17];
hold_my_vec(v);
let element = v.get(3);
println!("I got this element from the vector: {:?}", element);
}
error[E0382]: borrow of moved value: `v`
--> src/main.rs:6:19
|
4 | let v = vec![2, 3, 5, 7, 11, 13, 17];
| - move occurs because `v` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
5 | hold_my_vec(v);
| - value moved here
6 | let element = v.get(3);
| ^ value borrowed here after move
fn hold_my_vec<T>(_: Vec<T>) {}
fn main() {
let v = vec![2, 3, 5, 7, 11, 13, 17];
hold_my_vec(v);
let element = v.get(3);
println!("I got this element from the vector: {:?}", element);
}
use mini_redis::{client, Result};
#[tokio::main]
async fn main() -> Result<()> {
// Open a connection to the mini-redis address.
let mut client = client::connect(
"127.0.0.1:6379"
).await?;
// Set the key "hello" with value "world"
client.set("hello", "world".into()).await?;
// Get key "hello"
let result = client.get("hello").await?;
println!("got value from the server; result={:?}", result);
Ok(())
}
https://slides.com/esphen/rust-intro