Gary Guo
    • 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
      • Invitee
    • 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
    • Engagement control
    • 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 Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control 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
Invitee
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
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
Custom Smart Pointers in Rust === ## What do we need? Before we start exploring solution I think it's important to list what are the things that we need for smart pointers. Let's say that we have a smart pointer `MyPtr<T>` which is a wrapper around a pointer to T, and a type called `Foo`. Then we might have the following needs: 0. Be able to used as `self` type. ```rust impl Foo { fn foo(self: MyBox<Foo>) { /* ... */ } } ``` 1. Be able to call method on `Foo` with first argument being `&Foo` or `&mut Foo` ```rust let mut my_ptr: MyBox<Foo> = ...; my_ptr.foo(); // Able to call `Foo::foo(&Foo)` my_ptr.foo_mut(); // Able to call `Foo::foo_mut(&mut Foo)` ``` 2. Be able to call method on `Foo` with first argument being `MyPtr<Foo>` or `&MyPtr<Foo>`. ```rust let mut gc_ptr: Gc<Foo> = ...; gc_ptr.foo(); // Able to call Foo::foo(&Gc<Foo>) ``` 3. Be able to be coerced to an unsized type, or be trait upcasted. ```rust let my_ptr: MyBox<Foo> = ...; let my_ptr: MyBox<dyn Bar> = my_ptr; ``` 4. Be able to be used for dynamic dispatch (trait object). ```rust trait Bar { fn bar(self: MyBox<Self>); } let my_ptr: MyBox<dyn Bar> = my_ptr; my_ptr.bar(); // calls Foo::bar(MyBox<Foo>); ``` ## Current situation So what's the current situation? * For case 1, we already have `Deref` trait today. * For case 0 and 2, we have the `Receiver` trait, or the `arbitrary_self_types` feature. Currently, we require the custom type to implement `Deref` for the `Receiver` trait to be useful. * For case 3, we have the `CoerceUnsized` trait. * For case 4, we have the `DispatchFromDyn` trait. However, it's important to note, that while this trait can be implemented without `Receiver` trait, but it's useless. The [arbitrary self types RFC](https://github.com/rust-lang/rfcs/pull/3519) tries to address case 0 (and 2), without adressing case 3 and 4. It spents a lot of effort trying to make the case 2 extend to types that are not `Deref`. ## Evaluation First of all, I think it's important to note that, the case 0 (i.e. ability to make a custom type receiver), *should not* be a goal. It should be a *mean* that allows us to solve other cases. We don't need to allow more types to be put into `self: T` just for the sake of being able to do it, but rather we should focus on *why* we'd want to put things there. So, let's look at case 2-4 and see what can we gain from these (ignoring case 1 which is already stable). ### Method resolution It should be important to notice that case 2 and the other two are of different categories. Case 2 doesn't add any new power to the language, but rather just a syntactic sugar. It's already possible to just use `Foo::foo(&my_ptr)`. Case 2 provides us with a nice sugar to turn it into `my_ptr.foo()`, but that's only value that it provides. It should be noted that we already define quite a few methods on `*const T` or `Weak<T>`, and it can be a quite a disaster if we allow `weak.foo()` or `raw_ptr.foo()` because it * makes it a breaking change to add methods on `Weak`, or makes it a breaking change to add methods on `Foo` * makes it confusing to know which type provides which method. This won't be an issue for new types, but I think it's a bad idea to retrospectively tweak method resolution for existing types like `Weak` and raw pointers. ### Dynamic dispatch Case 3 and 4, on the other hand, provides *real* power to library authors. Currently, smart pointers that allow dynamic dispatch is a privilege that only standard library smart pointers enjoy. It's extremely difficult if not impossible to replicate this feature in 3rd party libraries, and even it's possible, it won't be as ergnomical. Different from case 2, there are value in extending dynamic dispatch to `*const T` and `Weak<T>`, and it is backward compatible. It should be noted that `DispatchFromDyn` even is already implemented for those types, but we just don't have a way to use them (we do hard-code raw pointers in `arbitrary_self_types` feature, but I don't think hardcoding is good). If we look at all types, we can see that they have different needs, | Types | 1 (Deref) | 2 (Method) | 3 (Unsize) | 4 (Dispatch) | | ------|---------- | ---------- | ---------- | ------------ | | `Box`/`Arc` | ✓ | ✓ | ✓ | ✓ | | `*const`/`*mut T` | ✕ | ✕ | ✓ | ✓ | | std `Weak` | ✕ | ― (too late to change) | ✓ | ✓ | | custom `Weak` | ✕ | ✓ | ✓ | ✓ | (There are definitely smart pointers that need 12 but not 34, but I can't think of any now) The sad thing, though, is that we entangled things a bit too much. For `DispatchFromDyn` to be useful, you need to implement `Receiver`, for which you need to implement `Deref`. So you have all of case 1, 2, 3, 4, or you have none of them, but there are scenarios where we need 3 & 4, but don't want the ability to do `Deref`. ## So what's the next step? The current self arbitrary types, both as current implemented and the new RFC, doesn't address the dynamic dispatch issue, which I think is more important than the symbol resolution. Furthermore, if we pursue self arbitrary self types without considering dynamic dispatch, this may make the entanglement worse and make it even harder to make dynamic dispatch work. I think a reasonable first step is to see how we can detangle receiver with dynamic dispatch. Perhaps we can lift the requirement that a method must have `self` to be used in trait object? I don't see a particular reason why ```rust trait Bar { fn bar(this: *const Self); } ``` can't be made object-safe and dispatched on `this` (i.e. lifting the `self` requirement, and dispatch on the first argument instead). You can then call this with `<dyn Bar>::bar(dyn_bar)`. Combining this with an arbitrary self types *without* pointers would cover *almost* all use cases, with the exception that we won't have the sugar to use method-calling syntax on methods defined on `T` that takes `Weak<T>`.

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