内置*安全*方式移出 Vec<T>? [英] Built in *safe* way to move out of Vec<T>?
问题描述
我一直在查看文档,到目前为止我还没有看到一个内置函数可以安全地将项目移出 Vec
.
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
存在,但这只是借用.Vec::remove
存在,虽然它确实移出了向量,但如果索引超出范围,它也会发生恐慌.所以,我有两个问题:
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:
- 从向量中移动项目的预期/好方法是什么?
remove(&mut self, index: usize) ->如果超出范围,T
会发生恐慌.恐慌的原因可能是什么?为什么不像remove(&mut self, index: usize) ->选项
?
- What is the intended/good way to move an item from a vector?
remove(&mut self, index: usize) -> T
panics if out of range. What might be the reason for panicking? Why isn't it implemented likeremove(&mut self, index: usize) -> Option<T>
?
推荐答案
如果您在 Rust 上下文中说安全,我们会想到内存安全..remove(i)
在常规 Rust 术语中当然是安全的,只是为了澄清.调用 panic!()
是安全.
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.
.remove(i)
和 .swap_remove(i)
的错误行为与使用 v[i]
索引向量相同code> 语法:如果 i
越界,则是程序员的错误,库函数会崩溃.这在错误处理指南中也称为合同违规子句.
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.
所以库背后的想法是,如果您知道 i
或 v.remove(i)
> 在边界内,您确实可以检查它是否正在使用 i <v.len()
或 v.get(i)
如果需要.
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.
还有另一个函数可以让你将一个元素移出向量而不会有恐慌的可能性,那就是 v.pop()
删除向量中的最后一项,返回 Vec
的选项
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>
.
这篇关于内置*安全*方式移出 Vec<T>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!