How to iterate over and filter an array?

In cases like this, it’s very useful to force the compiler to tell you the type of the variable. Let’s trigger a type error by assigning the closure argument to an incompatible type: array_iter.filter(|x| { let _: () = x; x == 2 }); This fails with: error[E0308]: mismatched types –> src/lib.rs:4:41 | 4 | …

Read more

How do I synchronously return a value calculated in an asynchronous Future?

Standard library futures Let’s use this as our minimal, reproducible example: async fn example() -> i32 { 42 } Call executor::block_on: use futures::executor; // 0.3.1 fn main() { let v = executor::block_on(example()); println!(“{}”, v); } Tokio Use the tokio::main attribute on any function (not just main!) to convert it from an asynchronous function to a …

Read more

How to test async functions that use Tokio?

Just replace #[test] with #[tokio::test] before any test function. If you use actix-web you can add actix_rt into Cargo.toml and #[actix_rt::test] before the test function #[tokio::test] async fn test_something_async() { let DB = setup().await; // <- the DB is impl std::future::Future type // the DB variable will be used to run another // async function …

Read more

Returning a closure from a function

As of Rust 1.26, you can use impl trait: fn make_adder(a: i32) -> impl Fn(i32) -> i32 { move |b| a + b } fn main() { println!(“{}”, make_adder(1)(2)); } This allows returning an unboxed closure even though it is impossible to specify the exact type of the closure. This will not help you if …

Read more