gpt4 book ai didi

rust - 当引用不需要时,为什么原始指针需要 const 关键字?

转载 作者:行者123 更新时间:2023-12-03 16:19:13 25 4
gpt4 key购买 nike

对于已注释掉的行,请引用下面的代码。它不能被 Rust 编译器编译,这意味着我们需要指定像 *const i32 这样的常量。显式用于 Rust 中的原始指针。但是对于对其指针对象不可变的引用,我们不需要像使用原始指针那样显式指定常量。那么,为什么 Rust 不使用更对称的方式来表达引用和原始指针的相同含义,因为引用实际上是引擎盖下的指针?

fn main() {
let x1: &i32;
let x2: &mut i32;
// let p1: *i32; // This line doesn't compile!!!
let p1: *const i32; // we need to specify the constness explicitly.
let p2: *mut i32;
}

最佳答案

早期版本的 Rust(1.0 之前)使用 *Tconst原始指针(与您注意的语法相同,今天不起作用)。 RFC 0068更名 *T*const T , 理由是使用 *T 更容易出错从现有 C 代码转录类型签名时:

The current difference in Rust unsafe pointers types with C pointers types is proving to be too error prone to realistically enable these optimizations at a future date. By renaming Rust's unsafe pointers to closely match their C brethren, the likelihood for erroneously transcribing a signature is diminished.


RFC 还指出(正如您所做的那样),这会导致引用和原始指针之间的命名不一致:

Today's unsafe pointers design is consistent with the borrowed pointers types in Rust, using the mut qualifier for a mutable pointer, and no qualifier for an "immutable" pointer. Renaming the pointers would be divergence from this consistency, and would also introduce a keyword that is not used elsewhere in the language, const.

关于rust - 当引用不需要时,为什么原始指针需要 const 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67145888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com