有没有办法以有意义的方式声明变量不可变?

Is there a way to declare a variable immutable in a meaningful way?

直到今天,我还认为在没有 mut 的情况下声明一个变量可以确保它在初始化后无法更改。

我认为这很棒,因为我一直对 C 和 C++ 中的 const 不能保证任何事情的方式感到不满。

我刚刚发现我错了:Rust 允许内部可变性(参见 std::cell)。它给了你一些保证,但不是我听到不可变时所期望和希望的。

有没有办法声明一些东西"really immutable"?

在 运行 次评估代码中防止内部可变性是不可能的(持续评估使这很容易,没有任何类型的突变)。您使用的任何您无法控制的类型都可能使用不安全代码来实现内部可变性。为了防止最常见的情况,您可以使用所谓的 "marker trait"。此特征没有其他目的,只是让您区分实现特征的类型和未实现特征的类型。

#![feature(optin_builtin_traits)]

use std::cell::{RefCell, Cell, UnsafeCell};
use std::sync::Mutex;

unsafe trait ReallyImmutable {}

unsafe impl ReallyImmutable for .. {}
impl<T> !ReallyImmutable for RefCell<T> {}
impl<T> !ReallyImmutable for Cell<T> {}
impl<T> !ReallyImmutable for UnsafeCell<T> {}
impl<T> !ReallyImmutable for Mutex<T> {}
impl<'a, T> !ReallyImmutable for &'a mut T {}
impl<T> !ReallyImmutable for *mut T {}
impl<T> !ReallyImmutable for *const T {}

这当然有一个缺点,即要求您将内部可变性列入黑名单,而不是将不可变类型列入白名单。所以你可能总是会错过一些东西。