slice是String的一部分引用。類似切片。
字符串slice
slice獲取值的使用權但是沒有得到值得所有權
fn main() {
let s = String::from("Hello world");
let hello = &s[0..5]; //[start, end)
let world = &s[6..11]; //[start, end);
println!("{},{}", hello, world);
let hello = &s[..5]; //[0, end)
let world = &s[6..]; //[start, len);
let string = &s[..]; //[0, len)
println!("{},{}, {}", hello, world, string);
let hello = &s[0..=4]; //[start, end]
let world = &s[6..=10]; //[start, end]
println!("{},{}", hello, world);
}
其他slice
fn main() {
let a = [1, 2, 3, 4, 5];
let slice = &a[1..3]; //類型是&[i32]
println!("{}, {}", slice[0], slice[1]);
}