Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

rust - Built in *safe* way to move out of Vec<T>?

I've been looking over the documentation, and so far I haven't seen a built in function to safely move an item out of a Vec.

Vec::get exists, but that just borrows. Vec::remove exists, and while that does move out of the vector, it also panics if the index is out of range. So, I have two questions:

  1. What is the intended/good way to move an item from a vector?
  2. remove(&mut self, index: usize) -> T panics if out of range. What might be the reason for panicking? Why isn't it implemented like remove(&mut self, index: usize) -> Option<T>?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...