TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Rust shenanigans: return type polymorphism

45 点作者 mrmagoo17大约 4 年前

3 条评论

hyperman1大约 4 年前
I was under the impression that this is something you get for free with Hindley-Millner: There is nothing in there that says: This works only for parameters. As long as there are enough hints left so the compiler can find exactly 1 correct type, the inference will work.<p>To rephrase this: Some languages have syntax for calling functions like this:<p><pre><code> returned=function(arg1,arg2) </code></pre> and some have it like this:<p><pre><code> function(arg1 in,arg2 in,returned out) </code></pre> You can mechanically transform between these 2 styles. The second style works with argument-only type inference, so the compiler has no reason to have problems with the first style.<p>Update: I played around with it - see <a href="https:&#x2F;&#x2F;godbolt.org&#x2F;z&#x2F;nfjz8hKa8" rel="nofollow">https:&#x2F;&#x2F;godbolt.org&#x2F;z&#x2F;nfjz8hKa8</a><p>I added a trait User with D6-&gt;i32 and D8-&gt;u8 implementations, and then this:<p><pre><code> let temp=Die::roll(); let _:u8=User::user(temp); </code></pre> The compiler can first decide which impl of User to use from the u8, namely the D8. This means it has to use the D8 variant of Die::roll. This compiles, even if the type of temp was never explicitly specified.<p>This means rustc is even more powerfull than the article implies. When using collect the type definition is <i>not</i> necessary, as long as the function contains enough hints to infer it.
评论 #26805553 未加载
评论 #26813401 未加载
Waterluvian大约 4 年前
I really love the incremental narrative style of this post. I got to go on the discovery ride with you and understood better than if you just explained the feature.
评论 #26805247 未加载
rurban大约 4 年前
I fail to understand the importance of this article, why it&#x27;s a shenigan. About every self respecting OO language honors and can infer return types (union or single), and follow properly the Liskov Substitution Principle (covariant returns, in opposite to args).<p>Next time another Rust fanboy will detect subtyping, and the strange behavior of different subtyping for return types. Inverse unification! Rust is special! Genius!<p>Liskov wrote that 1994.
评论 #26817149 未加载