问题描述
我有一个 &[T]
类型的变量 a
;如何获得对 a
子切片的引用?
I have a variable a
of type &[T]
; how can I get a reference to a subslice of a
?
举个具体的例子,我想得到 a
的前半部分和后半部分,前提是 a.len()
是偶数.
As a concrete example, I'd like to get the first and second halves of a
, provided a.len()
is even.
推荐答案
你使用切片语法:
fn main() {
let data: &[u8] = b"12345678";
println!("{:?} - {:?}", &data[..data.len()/2], &data[data.len()/2..]);
}
(试试这里)
一般语法是
&slice[start_idx..end_idx]
给出从 slice
派生的切片,从 start_idx
开始,到 end_idx-1
结束(即右侧索引处的项不包括在内).可以省略任何一个索引(甚至两个),这意味着相应的零或切片长度.
which gives a slice derived from slice
, starting at start_idx
and ending at end_idx-1
(that is, item at the right index is not included). Either index could be omitted (even both), which would mean zero or slice length, correspondingly.
注意,如果你想将某个位置的切片分割成两个切片,通常使用split_at()
方法会更好:
Note that if you want to split a slice at some position into two slices, it is often better to use split_at()
method:
let data = b"12345678";
let (left, right): (&[u8], &[u8]) = data.split_at(4);
此外,这是从另一个可变切片中获取两个可变切片的唯一方法:
Moreover, this is the only way to obtain two mutable slices out of another mutable slice:
let mut data: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8];
let data_slice: &mut [u8] = &mut data[..];
let (left, right): (&mut [u8], &mut [u8]) = data_slice.split_at_mut(4);
然而,这些基本的东西在关于 Rust 的官方书籍中有解释.如果你想学习 Rust,你应该从那里开始.
However, these basic things are explained in the official book on Rust. You should start from there if you want to learn Rust.
这篇关于如何获得子切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!