字符串slice是String类型中的部分引用
fn main() {
let s = String::from("hello,world");
// 语法一:左闭右开
let hello = &s[0..5]; // 因为slice是部分引用,自然需要使用引用符
println!("{}", hello); // hello
let world = &s[6..]; // world
println!("{}", world);
let all = &s[..]; // hello,world
println!("{}", all);
// 语法二:左闭右闭
let hello = &s[0..=4];
println!("{}", hello); // hello
let world = &s[6..=10]; // world
println!("{}", world);
}
字符串字面值就是slice,字面值简单来说就是直接表示值的数据。一般的字面值有字符串,数字,布尔,字符等
fn main() {
// 字符串slice
let s = "hello"; // 推导为 &str 类型
println!("{}",s);
let h = &s[0..=0];
println!("{}",h);
// 数字slice
let nums = [1,2,3,4]; // 推导为 [i32;4] 类型
let sub_nums = &nums[0..=1];
println!("{}",sub_nums[0]);
println!("{}",sub_nums[1]);
// 布尔slice
let bools = [false,true,false,false]; // 推导为 [bool;4] 类型
let sub_bools = &bools[0..=1];
println!("{}",sub_bools[0]);
println!("{}",sub_bools[1]);
}