I am not good at English. Sorry if there are any funny expressions.
Hi all.
I want to remove unboxed_closure
(unstable feature) from following code.
(However, I want to keep generality of callback
functions as much as possible.)
(Hard part for me is handling lifetimes around iter_from_vec
.)
#![feature(unboxed_closures)]
fn main() {
use std::slice::Iter;
let vec = vec![1, 2, 3];
let iter = callback::<_, _, Iter<i32>>(&vec, iter_from_vec);
assert!(iter.eq(vec.iter()))
}
fn iter_from_vec(x: &Vec<i32>) -> impl Iterator<Item = &i32> + '_ {
x.iter()
}
fn callback<F, I, O>(input: &I, f: F) -> <F as FnOnce<(&I,)>>::Output
where
F: for<'a> Fn<(&'a I,)>
{
f(&input)
}
Aside
About why I thought it could be done without unboxed_closure
.
I previously wrote the following code with errors.
fn main() {
let input = &42;
let result = callback(input, identity); // đĨ error!
assert_eq!(result, input);
}
fn identity(x: &i32) -> &i32 {
x
}
fn callback<F, I, O>(input: &I, f: F) -> O
where
F: for<'a> Fn(&'a I) -> O
{
f(input)
}
This error was repaired with unboxed_closure
.
#![feature(unboxed_closures)]
fn main() {
let input = &42;
let result = callback(input, identity);
assert_eq!(result, input);
}
fn identity(x: &i32) -> &i32 {
x
}
fn callback<F, I>(input: &I, f: F) -> <F as FnOnce<(&I,)>>::Output
where
F: for<'a> Fn<(&'a I,)>
{
f(input)
}
This error was repaired without unboxed_closure
too (But complex...).
fn main() {
let input = &42;
let result = callback(input, identity);
assert_eq!(result, input);
}
fn identity(x: &i32) -> &i32 {
x
}
fn callback<F, I>(input: &I, f: F) -> <F as FnHelper<&I>>::Output
where
F: for<'a> FnHelper<&'a I>
{
f(input)
}
trait FnHelper<I>: Fn(I) -> <Self as FnHelper<I>>::Output {
type Output;
}
impl<F, I, O> FnHelper<I> for F
where
F: Fn(I) -> O,
{
type Output = F::Output;
}
So I am wondering if there is a similar approach in this time.