Niko Matsakis
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # impl Trait everywhere ## Premise * impl Trait is a crucial Rust enabler * Our current support on stable is quite limited * Only applies to: * argument/return position for inherent functions/methods * argument position in trait methods * Disallows, I believe, [member constraints] * Also important for async code in particular * Allows one to return `async move` from within traits in some situations * Some places impl Trait is not allowed on nightly * Module level opaque types (`type Foo = impl Bar`) * Associated types * Some places impl Trait is not allowed on stable * Where clauses ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=817d9ba7db6e43ba50edd1186315416a)) * Impl fn sugar like `impl Fn(impl Debug)` ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=17b0591c82617a397fd2727105e6397e)) * Dyn fn sugar like `dyn Fn(impl Debug)` ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=bc20ce970af1849c0c1e26fa0077da95)) * Trait method return types * I would like to see an effort to stabilize impl Trait and "complete" it * Key steps * Make small-bore decisions (let's not discuss now) * e.g., do we permit turbofish to specify `impl Trait`? * If not, do we permit turbofish to specify the non-`impl Trait` type arguments of a function that uses `impl Trait`? * Reconcile the implementation inference details and decide on what we want * Stabilize `type Foo = impl Trait` at module level and as the value of associated types * Extend to return position in traits * Specify interaction of lifetime inference like `'_` with impl Trait (what does `T: impl Foo<'_>` mean?) * Extend `impl Trait` to all positions where it makes sense * * write-up the principle behind that * document why we have chosen not to extend it to the other positions * Related sugar and convenience * Eliding `type Foo = ...` in an impl if it is determined by a function return type * Some language questions I'd like to discuss (not all in this meeting) * Implementation inference differences * Trait return position considerations * impl Trait everywhere concept (I didn't get time to revisit this as I had hoped...) ## Prohibiting turbofish * Prohibiting turbofish does mean that using `impl Trait` has a specific downside * may become common wisdom that one should not use `impl Trait` in public APIs * Ordering issue: * relative to explicit type parameters * have to define an order * one possibility is just "syntactic order" * (what are other reasonable possibilities? e.g. using names of params, or some other kind of "path" thing?) * Does enable migration to/from impl Trait in simple cases Complex example: ```rust fn foo(x: impl Foo<Item = impl Bar, AnotherItem = impl Baz>); ``` Interacts with what we decide to do for `impl Trait` inside of `Fn(..)` style` ```rust fn foo(x: impl Fn(impl Debug)); fn foo(x: impl for<T: Debug> Fn(T)); ``` ```rust fn bar(x: impl IntoIterator<Item: Debug>); bar(None::<u32>) ``` Arguments against: * Never need it, because you can specify the value of the parameter * modulo `impl Foo<impl Bar>` * Nice to be able to have things that you can't specify * No need to define the ordering * Backwards compatible to make an (optional) extension Value of turbofish in general: * Usually I don't really want to specify the values of turbofish, except sometimes Possible incremental steps: - First support turbofishing explicit type parameters on a function that also uses `impl Trait`. (Requires deciding that *if* we support turbofishing `impl Trait` parameters,they come last.) - Then support turbofishing the `impl Trait` parameters. ## Implementation inference differences There are some limitations where the implementation doesn't seem to match the intent of the RFC. In particular, [RFC 2071 envisioned that](https://github.com/rust-lang/rfcs/blob/master/text/2071-impl-trait-existential-types.md#reference-existential-types) * within the scope of the opaque type (i.e., containing module), * any function that referenced it must completely specify its value, * but it *did* allow for "pass through". The actual implementation is more limited, and only really supports inferring the values for opaque types that appear in function return position. ### Const/static types For example, **const/static types** ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=fb8eac6b44c730fa5f9afbe0066cac96)): ```rust type Foo = impl std::fmt::Debug; const X: Foo = 22_u32; // Currently, errors static Y: Foo = 22_u32; // Also errors ``` #### Function arguments But also **function arguments**. The RFC lists an example like this example, which errors in our implementation: ```rust fn add_to_foo_2(x: Foo) { // ^^^ the use of `Foo` in arguments is treated as opaque let x: i32 = x; } ``` Similarly, the following currently errors ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=a9c5ade8f7659f5216b4dae0d2fcc28e)): ```rust #![feature(type_alias_impl_trait)] type Foo = impl std::fmt::Debug; fn test1(f: Foo) -> Foo { // ^^^ ^^^ we know we are inferring the value for this // | // but we treat the value of this opaquely let x: u32 = f; // and so we get an error here 22_u32 } fn main() { } ``` ### Partially inferred types The RFC states that each "item" (e.g., a function) that constrains an associated type must independently define its value: ```rust #![feature(type_alias_impl_trait)] type Foo = impl Sized; fn test1() -> Foo { // Constrains `Foo` to be `Option<_>`. None // Error -- both in RFC and in implementation } fn test2() -> Foo { Some(22_u32) // Works -- both in RFC and implementation } fn main() { } ``` Why this rule? * Reasoning complexity -- without this rule, you can have no single function that completely defines the type, rather than being able to reason about functions in isolation. * Could allow a system where we need "one witness with the complete type", though * Implementation complexity -- figuring out the value of an opaque type requires type-checking all the things in the module * although this is effectively required anyway, so not sure how much this tells you --nikomatsakis * Backwards compatible to remove it Digression: Explicit syntax to name the hidden type? Possible add-on. - Josh: having an explicit syntax for this would address all the use cases for which I'd normally want this kind of module-wide inference. ```rust type Foo = u32 as impl Sized; type Foo: Sized = u32; type Foo = impl Sized where Self = u32; // (backward compat?) // The `as` syntax is interesting: fn foo() -> i64 as impl Debug { 5 } // Should probably have `pub` somewhere to show which part of the type alias is public? ``` ### Associated types The RFC doesn't explicitly discuss associated types and impls, but there are interesting questions raised there as well. For example, do methods of an impl have to independently fully constrain the Opaque type? ```rust type Opaque = impl Sized; impl SomeTrait for () { // This is a "reference" to Opaque, and does not contrain it. type Item = Opaque; type Item<U> where <vec::IntoIter<u32> as IntoIterator<Item = Opaque>> = fn consume(x: Opaque) { // within an impl, each function or const/static operates independently } } ``` ### What do we know about `impl Trait` values before they are fully constrained? Or for passthrough code. For example: ```rust type Opaque = impl Debug; fn foo(x: Opaque) { format!("{:?}", x); // can we know that `Opaque: Debug` here? let _: u32 = x; // even as figure out what `Opaque` is *here*? } ``` Seems like the answer should be yes, but this will be mildly tricky for the implementation to resolve. Chalk could theoretically handle it but I'm not sure how well it would work in practice. ## Return position in traits ```rust trait Foo { fn foo(&self) -> impl Future; } trait Foo { type FooFuture: Future; fn foo(&self) -> Self::FooFuture; } where T: Foo<FooFuture: Send> ``` * type-of * just make an associated with a name based on the method * or a syntax like `Foo::foo::return` * downside -- no transition path to an explicit associated type * (unless `Foo::foo::return` can continue to work even after `foo` changes to use an associated type...) -- true ### Entangled issue: async fn in traits * Need some way to specify that the returned future is Send * don't have it, unless we address the above problem * but still want a shorthand ## Syntactic niceties * inferred associated types values when they appear in fn return position ```rust impl Iterator for () { fn foo(&self) -> X { // defines `type Item = X` implicitly } } // consider more complex examples like this one, that uses `impl Future` impl tokio::Service for MyType { fn request(&self) -> impl Future { async move { .. } } } ``` * some complexities around lifetimes, bounds (because impl can be more generic) ## RFC Record and summary, tracking issues * [RFC 1522] -- Conservative impl trait * Permit `impl Trait` in function argument and return position (excluding trait methods). * Estabished auto trait leakage and the basic principle of how the 'existential' type works. * [RFC 1951] -- Expand impl trait * Permit `impl Trait` in function argument position and function return position (excluding trait methods). * Designated that all type parameters are in scope for `impl Trait` plus any lifetimes that are explicitly named. * Did not propose any means of explicitly specifying the values for `impl Trait` in argument position (turbofish). * [RFC 2071] -- Impl trait existential types * Add the ability to create named existential types and support impl Trait in let, const, and static declarations. * Specified details of how existential type inference works * * [RFC 2515] -- Type alias impl trait * [Member constraints](https://github.com/rust-lang/rust/issues/61997) * [#63066] -- Rust tracking issue [RFC 1522]: https://github.com/rust-lang/rfcs/blob/master/text/1522-conservative-impl-trait.md [RFC 1951]: https://github.com/rust-lang/rfcs/blob/master/text/1951-expand-impl-trait.md [RFC 2071]: https://github.com/rust-lang/rfcs/blob/master/text/2071-impl-trait-existential-types.md [RFC 2515]: https://github.com/rust-lang/rfcs/blob/master/text/2515-type_alias_impl_trait.md [#61997]: https://github.com/rust-lang/rust/issues/61997 [#61773]: https://github.com/rust-lang/rust/issues/61773 [#60670]: https://github.com/rust-lang/rust/issues/60670 [#49287]: https://github.com/rust-lang/rust/issues/49287 [#45994]: https://github.com/rust-lang/rust/issues/45994 [#63066]: https://github.com/rust-lang/rust/issues/63066

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully