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 can I read user input in Rust?

Rust 1.x (see documentation): use std::io; use std::io::prelude::*; fn main() { let stdin = io::stdin(); for line in stdin.lock().lines() { println!(“{}”, line.unwrap()); } } Rust 0.10–0.12 (see documentation): use std::io; fn main() { for line in io::stdin().lines() { print!(“{}”, line.unwrap()); } } Rust 0.9 (see 0.9 documentation): use std::io; use std::io::buffered::BufferedReader; fn main() { let …

Read more