Rust之slice
at 2023-12-12 22:27:39, by 鹏城奋青
slice本质上就是部分借用(即引用),得出来的切片和源头有着密切关联:
(1)生命周期受限于借用源头。
(2)可读写也受限于借用源头。
一句话:但凡与“&“(借用/引用)相关的,必然与源头有这种摆不脱的关系。
fn main() {
let mut a: [i32; 3] = [1, 2, 3];
let a_slice: &mut [i32] = &mut a[..];
a_slice[0] = 123;
for n in a_slice {
println!("{}", n);
}
let b: [i32; 3] = [4, 5, 6];
let b_slice: &[i32] = &b[..];
for n in b_slice {
println!("{}", n);
}
}
语言级字符串类型用str关键字表示,字符串字面量硬编码在程序文件中,运行时被映射到只读内存区,对该类字符串的借用只能是不可变的,也就是&str类型。String类内部管理的内存可读写,因此它可以将内存字符串以可变借用拿出来,即能获得&mut str类型。对于&str和&mut str,我们叫它字符串切片,起因是str类型本质上是字符数组。
fn main() {
let s_literal: &str = "abc";
let s_literal_slice: &str = &s_literal[..];
println!("{}", s_literal_slice);
let mut s: String = String::from("def");
// pub fn as_mut_str(&mut self) -> &mut str
let s1: &mut str = &mut s.as_mut_str()[..];
unsafe {
let b1: &mut[u8] = &mut s1.as_bytes_mut()[..];
b1[0] = 99;
for c in s1.as_bytes() {
println!("{}", c);
}
}
println!("{}", s1);
}
入乡随俗,“&”以后我们还是说“借用”吧,说“引用”就显得C++了。
在rust中,当源代码不能编译时,基本上就是不该那样写。