Rust基础04-切片
切片
Rust 的另外一种不持有所有权的数据类型:切片(slice)
fn main() {
let s = String::from("Hello World");
let hello = &s[0..5];
//也可写作:
//let hello = &s[..5];
let world = &s[6..11];
//也可写作:
//let world = &s[6..];
//let world = &s[6..s.len()]
let whole = &s[..];//指向整个字符串
println!("{}, {}", hello, world);
println!("{}", whole);
}
字符串切片:
-
概念:指向字符串中一部分内容的引用
-
形式:[开始索引..结束索引]
开始索引就是切片起始位置的索引值
结束索引是切片终止位置的下一个索引值
-
注意:
- 字符串切片的范围索引必须发生在有效的 UTF-8 字符边界内
- 如果尝试从一个多字节的字符中创建字符串切片,程序会报错并退出
字符串字面值:
字符串字面值被直接存储在二进制程序中
let s = "Hello,World!";
变量 s 的类型是 &str ,它是一个指向二进制程序特定位置的切片, &str 是不可变引用,所以字符串字面值也是不可变的
将字符串切片作为参数传递:
fn main() {
let my_string = String::from("Hello world");
let wordIndex = first_word(&my_string[..]);
let my_string_literal = "hello world";
let wordIndex = first_word(my_string_literal);
}
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[..i];
}
}
&s[..]
}
其他类型的切片:
fn main() {
let a = [1, 2, 3, 4, 5];
let slice = &a[1..]
}