pointers - Difference in mutability between reference and box -
i'm trying understand rust pointer types , relation mutability. specifically, ways of declaring variable holds pointer , mutable -- i.e. can pointed other memory, , declaring data itself mutable -- i.e. can changed through value of pointer variable.
this how understand plain references work:
let mut = &5; // mutable pointer immutable data let b = &mut 5; // b immutable pointer mutable data
so a
can changed point else, while b
can't. however, data b
points can changed through b
, while can't through a
. do understand correctly?
for second part of question -- why box::new
seem behave differently? current understanding:
let mut = box::new(5); // mutable pointer mutable data let c = box::new(7); // c immutable pointer immutable data
new
should return pointer heap-allocated data, data points seems inherit mutability variable holds pointer, unlike in example references these 2 states of mutability independent! is how box::new
supposed work? if so, how can create pointer value mutable data on heap stored in immutable variable?
first, understand how references behave correctly. mut a
mutable variable (or, more correctly, mutable binding), while &mut 5
mutable reference pointing mutable piece of data (which implicitly allocated on stack you).
second, box
behaves differently references because fundamentally different references. name box
owning/owned pointer. each box
owns data holds, , uniquely, therefore mutability of data inherited mutability of box itself. yes, how box
should work.
another, more practical, way understand consider box<t>
equivalent t
, except of fixed size , allocation method. in other words, box
provides value semantics: moved around value , mutability depends on binding stored in.
there several ways create pointer mutable piece of data on heap while keeping pointer immutable. generic 1 refcell
:
use std::cell::refcell; struct x { id: u32 } let x: box<refcell<x>> = box::new(refcell::new(x { id: 0 })); x.borrow_mut().id = 1;
alternatively, can use cell
(for copy
types):
let x: box<cell<u32>> = box::new(cell::new(0)); x.set(1);
note above examples using so-called "internal mutability" should better avoided unless do need something. if want create box
mutable interior keep mutability properties, shouldn't. isn't idiomatic , result in syntactic , semantic burden.
you can find lot of useful information here:
- ownership
- references , borrowing
- mutability
- std::cell - internal mutability types
in fact, if have question such fundamental things mutability, explained in book :)
Comments
Post a Comment