rust - Is there a way to declare a variable immutable in a meaningful way? -
up until today, thought declaring variable without mut
made sure can not changed after initialization.
i thought great because resented way const
in c , c++ didn't guarantee anything.
i found out wrong: rust allows internal mutability (see std::cell). gives guarantees, not expect , wish when hear immutable.
is there way declare "really immutable"?
preventing interior mutability impossible in run-time evaluated code (constant evaluation makes easy, there's no mutation of kind). type use don't have control on might using unsafe code achieve interior mutability. prevent common cases can use called "marker trait". trait has no other purpose allow differentiate between types implement trait , types don't.
#![feature(optin_builtin_traits)] use std::cell::{refcell, cell, unsafecell}; use std::sync::mutex; unsafe trait reallyimmutable {} unsafe impl reallyimmutable .. {} impl<t> !reallyimmutable refcell<t> {} impl<t> !reallyimmutable cell<t> {} impl<t> !reallyimmutable unsafecell<t> {} impl<t> !reallyimmutable mutex<t> {} impl<'a, t> !reallyimmutable &'a mut t {} impl<t> !reallyimmutable *mut t {} impl<t> !reallyimmutable *const t {}
this has of course disadvantage of requiring blacklist interior mutability instead of white-listing immutable types. might miss something.
Comments
Post a Comment