Skip to content

RFC: implicit generic function arguments with bounds #302

Closed

Description

@rust-highfive

Issue by eddyb
Sunday Dec 29, 2013 at 19:35 GMT

For earlier discussion, see rust-lang/rust#11196

This issue was labelled with: B-RFC in the Rust repository


Using generic functions with trait bounds results in efficient code generation, at the cost of syntactic simplicity (compared to using trait objects).

Consider this snippet:

fn stringify<T: ToStr>(x: T) -> ~str {
    x.to_str()
}
// Making use of a hypothetical Fn trait.
fn map2fn<T, U, V, F1: Fn<T, U>, F2: Fn<U, V>>(x: T, f1: F1, f2: F2) -> V {
    f2(f1(x))
}

Now with trait bounds moved to argument types (creating implicit generic type parameters):

fn stringify(x: ToStr) -> ~str {
    x.to_str()
}
// Making use of a hypothetical Fn trait.
fn map2fn<T, U, V>(x: T, f1: Fn<T, U>, f2: Fn<U, V>) -> V {
    f2(f1(x))
}
// Or closures as sugar for Fn (unboxed!).
fn map2fn<T, U, V>(x: T, f1: |T| -> U, f2: |U| -> V) -> V {
    f2(f1(x))
}

Note that this would be limited to values as references or pointers would conflict with current syntax for trait objects.

However, optimizing &Trait in an argument type (or even a structure field? there is room for discussion here) to a generic (<T: Trait> ... &T) wouldn't cause any serious issues AFAICT.
And it would mean we can make the closure syntax be sugar for &Fn without losing backwards compatibility while allowing compile-time monomorphization.

Activity

  1. scottmcm commented on Jan 19, 2018

    @scottmcm
    Member

    I think this is universal_impl_trait, so closing. (I continue to trawl through least-recently-updated...)

  2. eddyb commented on Jan 19, 2018

    @eddyb
    Contributor

    @scottmcm Yeah, that's the explicit version of this. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions