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

科技回声

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

GitHubTwitter

首页

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

资源链接

HackerNews API原版 HackerNewsNext.js

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

Thoughts on compile-time function evaluation and type systems (2018)

41 点作者 lkurusa超过 2 年前

1 comment

nextaccountic超过 2 年前
&gt; Now, let us go one level up and look at the const type system. We have seen that comparing raw pointers can raise a CTFE error, so this is actually not a const-safe operation. Similar to casting pointers to integers, we have to make the const type system reject code that compares raw pointers. However, it seems like a shame to not even allow comparing two references for equality, after converting them to raw pointers! After all, references never dangle, so this is a perfectly const-safe operation.<p>&gt; Lucky enough, Rust already has an answer to the need to side-step the type system in controlled ways: unsafe blocks. Comparing raw pointers is not allowed by the const type system because it is not const-safe, but just like we allow run-time-unsafe operations to be performed in unsafe blocks, we can allow const-unsafe operations as well. So, we should be able to write the following:<p><pre><code> const fn ptr_eq&lt;T&gt;(x: &amp;T, y: &amp;T) -&gt; bool { unsafe { x as *const _ == y as *const _ } } </code></pre> If this is ever introduced, I hope that one would be able to mark whether an unsafe block is used because a const-safety restriction (like comparing two pointers for equality) or runtime-safety restriction (all other uses of regular, runtime unsafe)<p>Like this:<p><pre><code> const fn ptr_eq&lt;T&gt;(x: &amp;T, y: &amp;T) -&gt; bool { unsafe(const) { x as *const _ == y as *const _ } } </code></pre> edit: this same point was made in the Rust internals thread when the article was written, <a href="https:&#x2F;&#x2F;internals.rust-lang.org&#x2F;t&#x2F;thoughts-on-compile-time-function-evaluation-and-type-systems&#x2F;8004" rel="nofollow">https:&#x2F;&#x2F;internals.rust-lang.org&#x2F;t&#x2F;thoughts-on-compile-time-f...</a>