If you say safe in a Rust context, we think of memory safety. .remove(i)
is certainly safe in regular Rust terms, just to clarify. Calling panic!()
is safe.
The error behavior of .remove(i)
and .swap_remove(i)
is the same as for indexing a vector with v[i]
syntax: If i
is out of bounds, it's a programmer bug and the library functions panic. This is also called the contract violation clause in the error handling guidelines.
So the thought behind the library is that you only use v[i]
or v.remove(i)
if you know that i
is in bounds, and you can indeed check that it is using i < v.len()
or v.get(i)
if you want.
There's another function that allows you to move an element out of a vector without possibility to panic, and that is v.pop()
which removes the last item in the vector, returning Option<T>
for a Vec<T>
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…