第 4.3 节关于 The Rust 编程语言 的切片 has this paragraph :
String Literals Are Slices
Recall that we talked about string literals being stored inside the binary. Now that we know about slices, we can properly understand string literals:
let s = "Hello, world!";
The type of
s
here is&str
: it’s a slice pointing to that specific point of the binary. This is also why string literals are immutable;&str
is an immutable reference.
现在,正如他们之前介绍的那样,字符串切片是一对(某种形式的)包含一个指针和一个长度。对我来说,这一段(特别是“我们谈到了字符串文字被存储在二进制文件中”和“指向二进制文件的那个特定点”)似乎暗示着指针直接进入程序存储器。不是堆栈,也不是堆,而是处理器存储程序所包含的所有指令的实际位置。如果需要,装配的特定行。
这是真的吗?如果不是,他们还有什么意思,实际上是如何完成的?如果我稍后遇到类似的问题,我该如何自己解决这个问题?
最佳答案
这是真的 - &'static str
字符串文字嵌入在二进制文件本身中。这不是 Rust 独有的,例如C implementations often do the same thing .
引用 Rust Reference (强调我的):
A string literal is a string stored directly in the final binary, and so will be valid for the
'static
duration.Its type is
'static
duration borrowed string slice,&'static str
.
有专门设计用于查找此类字符串的程序,例如strings或者只是 grep --text
.
相关问题:
关于reference - `&str` 可以包含指向 Rust 中程序内存的指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51825063/