Passing around and evaluating rust closures
By : Senthil
Date : March 29 2020, 07:55 AM
may help you . There are two problems: one is a bug in Rust, the other is actually a problem with your code. The bug in Rust is inference with closures is (currently) horrible, one has to give them explicit types when one wants anything other than &fn. (One filing of this is #2190.) code :
pub fn flat_map<T, U>(v: &[T], f: &fn(t: &T) -> ~[U]) -> ~[U]
fn main() {
let list = get_list();
let res = list.flat_map(|f| (*f)());
println(res.to_str());
}
fn get_list() -> ~[~fn() -> ~[~str]] {
let f1: ~fn() -> ~[~str] = || ~[~"foo"];
let f2: ~fn() -> ~[~str] = || ~[~"bar"];
~[f1, f2]
}
|
Calling closures from an array in Rust
By : Kone Tidiane Youssep
Date : March 29 2020, 07:55 AM
will be helpful for those in need The .iter() method of vector yields immutable references, you need mutable ones to call the closure, thus you should use .iter_mut() : code :
fn main() {
let mut closures = [|x: int| x * x, |x| x + 1];
for closure in closures.iter_mut() {
println!("{}", (*closure)(10i));
}
}
-----
100
11
|
Struggling with closures and lifetimes in Rust
By : user5141720
Date : March 29 2020, 07:55 AM
help you fix your problem I think that is a function that accepts a closure (that itself accepts a pair and returns unit) and a pair and returns unit. I seem to have to double bracket things: is that correct? code :
use std::collections::HashSet;
fn iterNeighbors<F>(mut f: F, (i, j): (i32, i32)) -> ()
where
F: FnMut((i32, i32)) -> (),
{
f((i - 1, j));
f((i + 1, j));
f((i, j - 1));
f((i, j + 1));
}
fn nthLoop(n: i32, s1: HashSet<(i32, i32)>, s2: HashSet<(i32, i32)>) -> HashSet<(i32, i32)> {
if n == 0 {
return s1;
} else {
let mut s0 = HashSet::new();
for &p in &s1 {
let add = |p| {
if !(s1.contains(&p) || s2.contains(&p)) {
s0.insert(p);
}
};
iterNeighbors(add, p);
}
drop(s2);
return nthLoop(n - 1, s0, s1);
}
}
fn nth(n: i32, p: (i32, i32)) -> HashSet<(i32, i32)> {
let mut s1 = HashSet::new();
s1.insert(p);
let s2 = HashSet::new();
return nthLoop(n, s1, s2);
}
fn main() {
let s = nth(2000, (0, 0));
println!("{}", s.len());
}
|
Rust closures from factory functions
By : Birgül
Date : March 29 2020, 07:55 AM
should help you out The error says that names must outlive the static lifetime, this is because the boxed Fn has static lifetime. You have two options: code :
fn printer(names: Vec<&'static str>) -> Box<Fn() -> String>{
Box::new(move|| {
// ...
})
}
fn printer<'a>(names: Vec<&'a str>) -> Box<Fn() -> String + 'a>{
Box::new(move|| {
// ...
})
}
fn main() {
let names = vec!["foo", "bar", "baz"];
let print = printer(&names);
let result = print();
println!("{}", result);
do_other_thing(names.as_slice());
}
fn printer<'a>(names: &'a Vec<&str>) -> Box<Fn() -> String + 'a>{
Box::new(move || {
// this is more idiomatic
// map transforms &&str to &str
names.iter().map(|s| *s).collect()
})
}
|
Closures as a type in a Rust struct
By : DannyBTZ
Date : March 29 2020, 07:55 AM
will be helpful for those in need Struct::new doesn't have any parameter that depends on F, so the compiler is unable to infer what type it should use for F. If you called a method later that used F, then the compiler would use that information to figure out the Struct's concrete type. For example: code :
use std::hash::Hash;
use std::collections::HashMap;
pub struct Struct<T, F>
where T: Eq,
T: Hash,
F: Fn() -> T,
{
hash_map: HashMap<T, F>,
value: T,
}
impl<T, F> Struct<T, F>
where T: Eq,
T: Hash,
F: Fn() -> T,
{
pub fn new(init_value: T) -> Struct<T, F> {
Struct {
hash_map: HashMap::new(),
value: init_value,
}
}
pub fn set_fn(&mut self, value: T, func: F) {
self.hash_map.insert(value, func);
}
}
fn main() {
let mut a = Struct::new(0);
a.set_fn(0, || 1); // the closure here provides the type for `F`
}
fn main() {
let mut a = Struct::new(0);
a.set_fn(0, || 1);
a.set_fn(1, || 2);
}
error[E0308]: mismatched types
--> <anon>:33:17
|
33 | a.set_fn(1, || 2);
| ^^^^ expected closure, found a different closure
|
= note: expected type `[closure@<anon>:32:17: 32:21]`
= note: found type `[closure@<anon>:33:17: 33:21]`
note: no two closures, even if identical, have the same type
--> <anon>:33:17
|
33 | a.set_fn(1, || 2);
| ^^^^
help: consider boxing your closure and/or using it as a trait object
--> <anon>:33:17
|
33 | a.set_fn(1, || 2);
| ^^^^
pub struct Struct<T>
where T: Eq,
T: Hash,
{
hash_map: HashMap<T, Box<Fn() -> T + 'static>>,
value: T,
}
pub fn set_fn<F: Fn() -> T + 'static>(&mut self, value: T, func: F) {
self.hash_map.insert(value, Box::new(func));
}
|