I'm learning Rust, and there, they reason that the following (python-equivalent) code is unsafe:
vec = ['1', '2']
ref = vec[0]
vec.append('3')
The rationale is ref
is a pointer to element in vec
, however, vec
is being mutated in the same scope via push command, which could involve moving the object to a whole new place in memory where there is enough space, leading to ref
being a dangling pointer => therefore, compiler fails because of unsafe code.
I'm convinced by the logic, but exactly why is this never a problem in Python?
We still have vec
in the heap and ref
is a pointer, right?
CodePudding user response:
ref
is not a pointer to part of vec
. It stores a reference to a string object. The list object referred to by vec
also stores a reference to that string object. If the list needs to resize its underlying storage, it will copy the references it holds into a new buffer, but the string won't move, so ref
's reference can't be invalidated by this operation.