Last active
September 30, 2022 23:44
-
-
Save doorbash/9f7e8b44aeeb3cd6c8c720139ea5e119 to your computer and use it in GitHub Desktop.
Rust examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait X { | |
fn y(&self); | |
} | |
struct N { | |
foo: String, | |
} | |
impl X for N { | |
fn y(&self) { | |
println!("foo {}", self.foo); | |
} | |
} | |
struct M { | |
hello: String, | |
} | |
impl X for M { | |
fn y(&self) { | |
println!("hello {}", self.hello); | |
} | |
} | |
fn main() { | |
let mut x: Vec<Box<dyn X>> = Vec::new(); | |
x.push(Box::new(N { | |
foo: "bar".to_owned(), | |
})); | |
x.push(Box::new(M { | |
hello: "world!".to_owned(), | |
})); | |
for i in x { | |
i.y(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::time::Duration; | |
use async_std::task::{self, sleep}; | |
use futures::future::join_all; | |
use rand::prelude::*; | |
fn main() { | |
task::block_on(async { | |
join_all((0..100).into_iter().map(|i| async move { | |
let delay = rand::thread_rng().gen_range(1000..=2000); | |
sleep(Duration::from_millis(delay)).await; | |
println!("Hello from task {}", i); | |
}).collect::<Vec<_>>()).await; | |
}) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main(){ | |
let colors = vec!["red", "green", "blue", "brown", "black", "white", "yellow", "pink"]; | |
let new_colors:Vec<&str> = colors.into_iter().filter_map(|item| match item.starts_with('b') { | |
true => Some(item), | |
false => None, | |
}).collect(); | |
println!("{:?}", new_colors); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use actix_web::{App, HttpRequest, HttpServer, get}; | |
#[get("/")] | |
async fn index(_req: HttpRequest) -> String { | |
match _req.peer_addr() { | |
Some(val) => val.ip().to_string(), | |
None => String::new(), | |
} | |
} | |
#[actix_web::main] | |
async fn main() -> std::io::Result<()> { | |
HttpServer::new(|| { | |
App::new().service(index) | |
}) | |
.bind(("0.0.0.0", 4000))? | |
.run() | |
.await | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn print_type_of<T: ?Sized>(_: &T) { | |
println!("{}", std::any::type_name::<T>()) | |
} | |
fn main() { | |
print_type_of("hello World!"); | |
print_type_of(&1); | |
print_type_of(&1.8) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use tokio::net::TcpListener; | |
use tokio::io::{self, AsyncReadExt, AsyncWriteExt}; | |
#[tokio::main] | |
async fn main() -> io::Result<()> { | |
let listener = TcpListener::bind("0.0.0.0:8080").await?; | |
loop { | |
match listener.accept().await { | |
Ok((mut socket, socket_addr)) => { | |
println!("new connection from {:?}", &socket_addr); | |
tokio::spawn(async move { | |
// let mut buf: [u8; 1024] = [0; 1024]; | |
let mut buf = vec![0; 1024]; | |
loop { | |
let n = match socket.read(&mut buf).await { | |
Ok(x) => x, | |
Err(err) => { | |
println!("error while reading socket: {}", err); | |
break; | |
} | |
}; | |
if n == 0 { | |
return; | |
} | |
socket.write_all(&buf).await.expect("error while writing on socket"); | |
} | |
}); | |
} | |
Err(err) => { | |
println!("error while accepting new connection: {}", err); | |
continue; | |
} | |
}; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::thread; | |
use std::thread::JoinHandle; | |
use std::time::Duration; | |
use rand::prelude::*; | |
fn main() { | |
let thread_handles = (1..=100).map(|i| { | |
let delay = rand::thread_rng().gen_range(1000..=2000); | |
let builder = thread::Builder::new().name(format!("custom-{}", i)); | |
builder.spawn(move || { | |
thread::sleep(Duration::from_millis(delay)); | |
println!("Delay {} ms Done! Thread name: {}", delay, thread::current().name().unwrap()); | |
}).unwrap() | |
}).collect::<Vec<JoinHandle<_>>>(); | |
for h in thread_handles { | |
let _ = h.join(); | |
} | |
println!("Job done"); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use futures::future::join_all; | |
use tokio::time::{sleep, Duration}; | |
use rand::prelude::*; | |
#[tokio::main] | |
async fn main() { | |
join_all((0..100).into_iter().map(|i| async move { | |
let delay = rand::thread_rng().gen_range(1000..=2000); | |
sleep(Duration::from_millis(delay)).await; | |
println!("Hello from task {}", i); | |
}).collect::<Vec<_>>()).await; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Concat { | |
fn concat(&self, input2: & str) -> String; | |
} | |
impl Concat for &str { | |
fn concat(&self, input2: & str) -> String { | |
format!("{} {}", self.to_string(), input2.to_string()) | |
} | |
} | |
fn main() { | |
let a = "hello"; | |
let b = "world!"; | |
println!("{}", a.concat(b)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment