TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Type-checked keypaths in Rust

81 pointsby pcr910303almost 3 years ago

7 comments

lnyngalmost 3 years ago
I created something similar for our project “below” (<a href="https:&#x2F;&#x2F;github.com&#x2F;facebookincubator&#x2F;below&#x2F;blob&#x2F;main&#x2F;below&#x2F;below_derive&#x2F;src&#x2F;lib.rs" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;facebookincubator&#x2F;below&#x2F;blob&#x2F;main&#x2F;below&#x2F;b...</a>).<p>The program collects system resource metrics into a data structure and we need to display the fields with different styles and formats. In order to decouple the data structure from rendering, Queriable (Keyable) and FieldId (combine KeyPath + mirror struct into enum) are used. I will definitely like to checkout the KeyPath implementation as it seems more general.
terhechtealmost 3 years ago
Typed Keypaths are one of the Swift language features which I really miss in any other language. They&#x27;re incredibly powerful because it is possible to compose them. Imagine a struct or class `Item` with a `user` field and the `User` has an `age` of `Int`:<p><pre><code> &#x2F;&#x2F; Keypath&lt;Item, User&gt; (from Item to User) let item_user = \Item.user &#x2F;&#x2F; Keypath&lt;User, Int&gt; (from User to Int) let user_age = \User.age &#x2F;&#x2F; Keypath&lt;Item, Int&gt; (from Item to Int) let item_age = item_user.appending(user_age)</code></pre>
评论 #31891120 未加载
评论 #31892424 未加载
pornelalmost 3 years ago
I think it may be possible to make it even more of a compile-time construct if uglier types were an option. Instead of holding a `Vec&lt;PathComponent&gt;` it could have been a list made out of nested types: `Path&lt;First, Path&lt;Second, Path&lt;Third, Last&gt;&gt;&gt;&gt;`.
SnowflakeOnIcealmost 3 years ago
I had not heard of keypaths before. They seem to provide functionality similar to lenses in Haskell.
评论 #31890872 未加载
评论 #31890780 未加载
sfvisseralmost 3 years ago
Are keypath like Haskell lenses? First class composable getters&#x2F;setters?<p>Or just the getter part?
ekiauhcealmost 3 years ago
Good article, thanks!<p>There is similar concept for json <a href="https:&#x2F;&#x2F;goessner.net&#x2F;articles&#x2F;JsonPath&#x2F;" rel="nofollow">https:&#x2F;&#x2F;goessner.net&#x2F;articles&#x2F;JsonPath&#x2F;</a><p>We heavily using it for validation error messages. Like<p><pre><code> { &quot;error&quot;: &quot;wrong value&quot;, &quot;path&quot;: &quot;foo&#x2F;bar[1]&#x2F;prop&quot; }</code></pre>
评论 #31892215 未加载
评论 #31890988 未加载
mkeedlingeralmost 3 years ago
This is quite cool, I&#x27;m just having a hard time imagining when I would use it.
评论 #31899188 未加载