计算机是如何存储字符串的?
在 Rust 中,字符串使用 UTF-8 编码
&str
vs str
let string: str = "banana";
cannot compile.str
动态大小,编译器不知道它的大小str
defines a slice of a block of data in memory which are meant to be interpreted as a sequence of characters and that’s all. It is uncertain where it is stored and how long that slice would be. This is why we can not use this type in a plain way in the time of writing.&str
: shared reference to str
let string: &'static str = "banana";
&
always points to valid data and that data stays immutable under it.&mut str
mutable reference can be used if the pointer points to the heap.String
: vector of characters
let mut banana_string: String = String::from("banana");
let mut cherry_string: String = String::from("I want a cherry");
banana_string += " ";
cherry_string += &banana_string;
&String
: pointer to String
Box<&str>
allocate on heap and take a pointer
let string: Box<&str> = Box::new(“banana”);
C/C++ 使用 null-terminated \\0
字符串
Rust 使用 fat pointers or heap-allocated structs
https://rustwiki.org/zh-CN/book/ch15-02-deref.html#函数和方法的隐式解引用强制转换
String
→ &str
fn hello(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
let m = Box::new(String::from("Rust")); // type: Box<String>
hello(&m); // &Box<String> -> &String -> &str
}