Can array lengths be inferred in Rust?

_ can only be used in two contexts: in patterns, to match a value to ignore, and as a placeholder for a type. In array types, the length is not a type, but an expression, and _ cannot be used in expressions. What you can do, though, is append f32 to only one of the … Read more

How can I distinguish between a deserialized field that is missing and one that is null?

Building off of E_net4’s answer, you can also create an enum for the three possibilities: #[derive(Debug)] enum Patch<T> { Missing, Null, Value(T), } impl<T> Default for Patch<T> { fn default() -> Self { Patch::Missing } } impl<T> From<Option<T>> for Patch<T> { fn from(opt: Option<T>) -> Patch<T> { match opt { Some(v) => Patch::Value(v), None => … Read more

Can you clone a closure?

Rust 1.26 Closures implement both Copy and Clone if all of the captured variables do. You can rewrite your code to use generics instead of a boxed trait object to be able to clone it: use std::thread; #[derive(Clone)] struct WithCall<F> { fp: F, } impl<F> WithCall<F> where F: Fn(i8, i8) -> i8, { pub fn … Read more

Return an async function from a function in Rust

Returning a function Returning the actual function pointer requires heap allocation and a wrapper: use std::future::Future; use std::pin::Pin; pub async fn some_async_func(arg: &str) {} pub fn some_async_func_wrapper<‘a>(arg: &’a str) -> Pin<Box<dyn Future<Output=()> + ‘a>> { Box::pin(some_async_func(arg)) } pub fn higher_order_func<‘a>(action: &str) -> fn(&’a str) -> Pin<Box<dyn Future<Output=()> + ‘a>> { some_async_func_wrapper } Why boxing? higher_order_func … Read more

How to concatenate static strings in Rust

Since I was essentially trying to emulate C macros, I tried to solve the problem with Rust macros and succeeded: macro_rules! description { () => ( “my program” ) } macro_rules! version { () => ( env!(“CARGO_PKG_VERSION”) ) } macro_rules! version_string { () => ( concat!(description!(), ” v”, version!()) ) } It feels a bit … Read more