Skip to content

Instantly share code, notes, and snippets.

@doorbash
Last active September 30, 2022 23:44
Show Gist options
  • Save doorbash/9f7e8b44aeeb3cd6c8c720139ea5e119 to your computer and use it in GitHub Desktop.
Save doorbash/9f7e8b44aeeb3cd6c8c720139ea5e119 to your computer and use it in GitHub Desktop.
Rust examples
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();
}
}
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;
})
}
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);
}
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
}
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)
}
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;
}
};
}
}
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");
}
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;
}
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