These are chat archives for rust-lang/rust

16th
Sep 2018
Ash
@ashthespy
Sep 16 2018 17:48 UTC
Is it possible to write a 'generics' version of a closure? I have some simple athematic that I have to perform on different int types
Ryan
@rnleach
Sep 16 2018 18:04 UTC
@ashthespy I've read a couple of books on rust and never saw anything like that, so I don't think there is.
Any work-around I can think of negates the benefits of a closure, like capturing the surrounding environment. If you don't need that you could just write a generic function and use that.
Ash
@ashthespy
Sep 16 2018 18:27 UTC
that would be an option indeed. Thanks!
Zakarum
@omni-viral
Sep 16 2018 19:03 UTC
@ashthespy unfortunately closure inplements the first Fn* trait bound it encounters.
If closure is passed as argument to generic method then it implements Fn bound of the type parameter.
If you bind closure to variable and call it later it implements one of Fn* depending on how you call it. Only first call counts.
Closure never implements more than one Fn* trait (except HKLB).
And since implementing Fn* trait for generic argument is the same as implement multiple Fn* traits for different argument types - closure can't do it either.
Carl Fredrik Samson
@cfsamson
Sep 16 2018 23:38 UTC

Hello, I need some help here solving a problem with closures. I have this:

  let mut varegrupper: Vec<Varegruppe> = vec![];
    let future = SqlConnection::connect(conn_str).and_then(|conn| {
    conn
      .simple_query("SELECT * from nxDw.dbo.Varegr")
      .for_each(|row: QueryRow| {
        let r1: &str = row.get(0);
        let r2: &str = row.get(1);
        let r3: &str = row.get(2);

        &varegrupper.push(Varegruppe::new(r1, r2, r3));
        Ok(())
      })
  });

  match current_thread::block_on_all(future) {
    Ok(_) => Ok(varegrupper),
    Err(e) => Err(e),
  }
}

And i get a cannot move out ofvaregrupperbecause it is borrowed error. I know how that works, but I see no way of solving it...

If I create a "scope" around the closure, then futures goes out of scope before the final match...