-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Provide wrappers over Box<Fn> #20878
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
Comments
What's the benefit of the Proxy type over just using an |
A proxy is the same type while arguments type and return type are the same, thus makes it possible to write a |
@bombless You can do the same thing by using regular trait objects, like so: #![feature(box_syntax)]
#![allow(unstable)]
fn main(){
let celebrate: Box<Fn(i64)> = box |&: num: i64| {
println!("Feels great to implement C++ std::function in {} lines.", num)
};
let lucky_number: Box<Fn(i64)> = box |&: num: i64| {
println!("My lucky number is {}", num)
};
let func = if std::rand::random() { celebrate } else { lucky_number };
func(25)
} You can even avoid the type annotations in a lot of cases. |
@reem For my experience, annotations cannot be avoided in most cases. |
Seems like this bug just amounts to "closures are unergonomic", then? |
"conversion to trait objects is verbose and unergonomic" probably, which I have definitely experienced. |
@gankro We can call it a feature, and I think the issue is the lack of relative facilities. |
@reem Yeah maybe things will change once type inference is improved. |
#18875 |
nikomatsakis@152d623#diff-0 |
It seems the proxy type thingy serves no purpose. Sometimes, a function is all you need: #![feature(unboxed_closures, box_syntax)]
#![allow(unstable)]
fn anyfunc<'a, Args, Ret, F>(closure: F) -> Box<Fn<Args, Ret> + 'a>
where F: Fn<Args, Ret> + 'a {
box closure
}
fn main(){
let celebrate = anyfunc(|&: num: i64| {
println!("Feels great to implement C++ std::function in {} lines.", num)
});
let lucy_number = anyfunc(|&: num: i64| {
println!("My lucky number is {}", num)
});
let func = if std::rand::random() { celebrate } else { lucy_number };
func(25)
} It's actually similar to what you would do in C++: write a function template à la |
I agree with @reem, @gankro, and @sellibitze in that this may just be an issue of ergonomics as boxed trait objects/closures sound like they do what you already want. Could you open a new issue more focused on the ergonomics of boxed closures if you're concerned? Thanks! |
Something like this:
Or is it part of the plan? :p
The text was updated successfully, but these errors were encountered: