crumblingstatue
    • 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
NOTE: This article is currently under a rewrite with a new example. Therefore it might not make much sense at places. Please wait until I finish rewriting the article. # My thoughts on (and need for) partial borrows I am a [long time advocate](https://github.com/rust-lang/rfcs/issues/1215#issuecomment-333316998) for partial borrows. Frustrated by Rust's lack of support for them, I keep bringing the topic up on the Rust Discord server, annoying people, and never really achieving anything. So in this post, I will try to collect all my thoughts on partial borrows, and stop pestering people with them once and for all. To be exact, I will focus on **methods**, as I think they are by far the biggest use case for partial borrows, and what I always end up needing. ## The problem I have been suffering from methods borrowing every field for a long time. It comes up a lot when I'm developing applications that have complex interactions between components. Since I'm terrible at thinking up examples, I will show an example from one of my projects, a [GUI hex editor](https://github.com/crumblingstatue/hexerator) with a [lot of features](https://github.com/crumblingstatue/hexerator/blob/main/features.md). My hex editor supports multiple configurable layouts, which can show different parts of a file in different ways. ![](https://github.com/crumblingstatue/hexerator/raw/main/screenshots/bookmarks.png) To achieve this, I have a type that holds the information on how to display a binary file. ```rust #[derive(Default)] pub struct HexState { pub ui: HexUi, pub meta_state: MetaState, } ``` It has two fields: - `meta_state`, which holds meta-information about the data, like different layouts that can present the data in an easy to grasp way. - `ui`, which holds the ui state, like which layout is active Then, I have a method that switches the active layout: ```rust impl HexState { pub(crate) fn switch_layout(&mut self, k: LayoutKey) { self.ui.current_layout = k; // Set focused view to the first available view in the layout if let Some(view_key) = self.meta_state.meta.layouts[k] .view_grid .get(0) .and_then(|row| row.get(0)) { self.ui.focused_view = Some(*view_key); } } } ``` So far so good. Let's try to call it in a non-trivial context. In the following code, I have a UI that presents a list of layouts, and if a layout in the list is clicked, that layout is set. ```rust for (k, v) in &app.hex.meta_state.meta.layouts { if ui.selectable_label(win.selected == k, &v.name).clicked() { win.selected = k; app.hex.switch_layout(k); } } ``` ``` error[E0502]: cannot borrow `app.hex` as mutable because it is also borrowed as immutable --> src/gui/layouts_window.rs:32:17 | 29 | for (k, v) in &app.hex.meta_state.meta.layouts { | -------------------------------- | | | immutable borrow occurs here | immutable borrow later used here ... 32 | app.hex.switch_layout(k); | ^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here ``` The borrow checker cannot see that the `switch_layout` method only needs the `layouts` part of `MetaState`. ## The solution How do we solve the problem of a method call borrowing every field? Well, the most obvious solution is not to borrow every field. ```rust= for (k, v) in &app.meta_state.meta.layouts { if ui.selectable_label(win.selected == k, &v.name).clicked() { win.selected = k; App::switch_layout(&mut app.hex_ui, &app.meta_state.meta, k); } } ``` Problem solved, right? ## Problems with the solution What's so bad about this that it raises a need for partial borrows? The short answer is that it makes the code less [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). Let's think about what properties makes methods so nice, and why this solution breaks them. I'll just call them **the three nicenesses** for lack of a better term: ### Niceness 1: It's obvious which parameters belong to your type With `fn put_char(&mut self, ch: u8);`, it's obvious that term wants mutable access to itself, in order to achieve whatever it wants with `ch`. With `fn put_char(cells: &mut Vec<u8>, width: &u16, height: &mut usize, cursor: &mut Cursor, ch: u8)`, it's not quite so obvious anymore. Which one of these belong to `Term`, and which ones are the free parameters? What if you call `put_char` with arguments that are not part of `Term`? There will be bugs, because `put_char` is designed to update the state of the `Term` itself. ### Niceness 2: You don't have to repeat the types of your fields With `fn put_char(&mut self, ch: u8)`, you never have to redeclare the types of `Term`'s fields. With `fn put_char(cells: &mut Vec<u8>, width: &u16, height: &mut usize, cursor: &mut Cursor, ch: u8)`, you have to specify all the types of your fields again. Now you have to keep in sync two (or more if you have multiple such methods) type annotations for your fields. What if your field has a complex type, like `field: &mut Option<Vec<Mutex<SomeOtherType>>>`? Type aliases help, but it should't be necessary to introduce a type alias because a single field has that type. ### Niceness 3: Call site ergonomics I think this one speaks for itself. Which one is more pleasant to write and read? ```rust= Self::put_char( &mut self.cells, &self.width, &mut self.height, &mut self.cursor, c, ) ``` vs. ```rust= self.put_char(c) ``` The former can build up fatigue quickly if the function is called in a lot of places. ## The real solution: Partial borrowing methods Can we have the best of both worlds? Have a method only borrow a chosen subset of fields, while retaining all **the three nicenesses** of methods? This concept is called *partial borrows*. Below, I'll try to give an example of one possible way it could look like, as well as detail some of the drawbacks and why such a design hasn't been accepted yet. ### Partial borrowing method concept: self.field parameters We could extend the `self` parameter syntax to allow borrowing individual fields, while expressing that these are fields of this type. ```rust= fn put_char(&mut self.cells, &self.width, &mut self.height, &mut self.cursor, ch: u8) { self.extend_while_cursor_past(); self.cells[self.cursor.index(self.width)] = ch; self.cursor.x += 1; if self.cursor.x >= self.width { self.cursor.x = 0; self.cursor.y += 1; } } ``` Calling it would be as simple as calling a normal `&mut self` method. ```rust= pub fn feed(&mut self, data: &[u8]) { self.ansi_parser.advance(data, |cmd| match cmd { TermCmd::PutChar(c) => self.put_char(c), _ => todo!() }); } ``` You may have noticed that we are calling a method inside `put_char`. Don't worry, it's also using self.field parameters: ```rust= fn extend_while_cursor_past(&mut self.cells, &mut self.cursor, &self.width, &mut self.height) { while self.cursor.y >= self.height { self.extend(); } } ``` And so on: ```rust= fn extend(&mut self.cells, &self.width, &mut self.height) { self.cells.extend(std::iter::repeat(b' ').take(self.width as usize)); self.height += 1; } ``` This retains all **the three nicenesses** of methods: 1. Knowing which parameters are part of our type 2. Not having to repeat field type annotations 3. Being ergonomic to write/read at the call site. ## Problems with partial borrows Okay, cool. But if partial borrows are so great, how come an RFC wasn't accepted yet? Unfortunately, partial borrows aren't all rainbows and sunshine either. Here are some problems that I can currently recall: ### New syntax This one is kinda obvious, but complicating the grammar of the language needs a strong enough motivation. Are the benefits of partial borrows worth making the syntax more complex? My answer is a very strong yes. ### Borrows become less obvious at a glance. Normal function call: ```rust= Self::put_char( &mut self.cells, &self.width, &mut self.height, &mut self.cursor, c, ) ``` It is quite clear at a glance what fields this call borrows. Partial method call: ```rust= self.put_char(c); ``` Is this a normal method or a partial method? What fields is it borrowing? For the answer, you have to look at the definition of `put_char`. In my opinion, this is not a big enough problem, because the compiler will yell at you if you cause any borrow issues, like always. What about diagnostics? The compiler could easily expand a partial method call so that it's easy to show where a borrow conflict occurs. ```rust= self.put_char(c); Diagnostic output: self.put_char( &mut self.cells, &self.width, ^^^ The borrow conflict occurs here &mut self.height, &mut self.cursor, c, ) ``` ### The elephant in the room: Visibility and semver hazards This is the most often brought up argument against partial borrows. #### Private fields What if we want to borrow a private field partially? If we put it in the signature of a partial method, its existence will be exposed to the public! While this is not ideal, in my opinion it's better than the alternative of making the field public. While the existence of the field is now publicly known, read and write access still remains private, so invariants will not be broken by this. And by far the most important part of privacy is protecting invariants. Semver is secondary (in my opinion). However, I do understand it is a semver hazard, and that's a valid problem to consider. There are some alternate solutions being discussed, like "borrow regions" or "borrow groups" that would abstract away the existence of fields. #### etc. To be honest, I don't quite grasp all the semver arguments against partial borrows. Just know that it's the most common and strong argument against partial borrows. If semver turns out to be an unsolvable problem (I hope not), I would be more than willing to accept partial borrows being restricted to intra-crate APIs, that is, APIs that are not reachable from outside of the current crate (think `pub(crate)`). This would still solve 99% of my pain, which usually comes up when working on complex internals, and not when designing public APIs. ## Conclusion While this post doesn't propose a concrete design for partial borrows, I hope I have convinced enough people that this is a problem worth solving, and shouldn't be dismissed by telling people to restructure their code. It is by far my biggest frustration with Rust, one that constantly sucks joy out of Rust programming for me. I hope I'm not alone in feeling this way! And I hope that if a solution does surface, it retains ***the three nicenesses*** of methods, as detailed above. Thanks for bearing with me, and Happy Rusting! Further reading: - https://smallcultfollowing.com/babysteps//blog/2021/11/05/view-types/ - https://github.com/rust-lang/rfcs/issues/1215

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