学习自 rust圣经
切片:全在栈上的对象,一个指针+一个长度
fn main() {
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
}
world:

- 四种不同的类型:String(如上图的s),&String(如下图的s),str(如下一段代码的hello,字符内容是硬编码在可执行文件中的),&str(字符串切片,如上图的world)

- 其中String和&str用得很多
- 都是utf-8编码,每个字符所占的字节数是变化的(1 - 4)
- 而Rust 中的字符是 Unicode 类型,每个字符占据 4 个字节内存空间
- 注意字符串切片是以字节为单位取(因此比如下述,一个中文是3个字节,下述会有问题index 2 is not a char boundary
fn main() {
let hello = "中国人";
let s = &hello[0..2];
}
- 如何将 String 类型转为 &str 类型呢?取引用即可。这种灵活用法是因为 deref 隐式强制转换
fn main() {
let s = String::from("hello,world!");
say_hello(&s);
say_hello(&s[..]);
say_hello(s.as_str());
}
fn say_hello(s: &str) {
println!("{}",s);
}