How to express lifetime constraints for closures which take and return references?

Advertisements I have sketched out an example problem in the Rust playground. For reference, I will provide the full code at the end of this question. I have attempted to write the following function. fn get_longest_time_window(&self) -> Option<u64> { let lambda = |lhs: &Element, rhs: &Element| -> &Element { return if lhs.time_window >= rhs.time_window {… Read More How to express lifetime constraints for closures which take and return references?

Rust no two closures, even if identical, have the same type

Advertisements How do to put two closures with the same definition into a Vec? Here is a minimal reproducible example: fn main() { let mut vec = Vec::new(); vec.push(Box::new(|| println!("test"))); vec.push(Box::new(|| println!("test2"))); vec.iter().for_each(|f| (f)()); } Which failed on compiling with following error: error[E0308]: mismatched types –> src/main.rs:4:23 | 3 | vec.push(Box::new(|| println!("test"))); | — the… Read More Rust no two closures, even if identical, have the same type

Why I cannot use string methods inside groovy closure? – no candidate for method call

Advertisements I have simple hashmap and want to manipulate it but IDE does not recognize the methods. Completely new to Groovy so not sure what is wrong. def percentages = [ "x1" : "20%", "x2" : "30%", "x3" : "0.4", "x4" : "50%", "x5" : "0.6"] percentages.each { val -> if(val[2].endsWith("%")) { val[2].deleteCharAt(val.length()-1) println val… Read More Why I cannot use string methods inside groovy closure? – no candidate for method call

Using async closure as lambda functions is a bit hard

Advertisements I’m trying to reproduce an error I’m having on my small app in Rust. I’m trying to use async closure as lambda functions (very tipical in other languages). But I just found out that this is a bit difficult in Rust: REPL: https://www.rustexplorer.com/b/bcwggm. Error: error: lifetime may not live long enough –> src/main.rs:55:9 |… Read More Using async closure as lambda functions is a bit hard

Inability to capture by Clone prevents some closures from being pure functions that otherwise could/should be. Any workaround?

Advertisements Consider the following: use std::ops::Fn; fn require_picky_callback( cb : impl Fn() -> () + ‘static) { } fn main() { let s = String::from("Rust"); … let s_copy = s.clone(); let cb = move || { s_copy; }; require_picky_callback(cb); } If String in this example were replaced with a Copy-able type such as int, this… Read More Inability to capture by Clone prevents some closures from being pure functions that otherwise could/should be. Any workaround?