实现说明
include_str 编译期嵌入文本可以归结为函数 main。
使用要点
- 每一步打印都带着自己的标签:
embedded bytes:、package、same length:。
常见问题
运行「include_str 编译期嵌入文本」会打印什么?
运行文件本身,embedded bytes:、package、same length: 这些前缀各对应一段演示逻辑。
核心语句
.unwrap_or("name = <missing>");
代码示例
// include_str! embeds text at compile time and yields a &'static str
const MANIFEST: &str = include_str!("../Cargo.toml");
fn main() {
println!("embedded bytes: {}", MANIFEST.len());
let name_line = MANIFEST
.lines()
.find(|line| line.trim_start().starts_with("name ="))
.unwrap_or("name = <missing>");
println!("package {name_line}");
// include_bytes! 得到 &'static [u8; N],适合非文本资源
let raw: &[u8] = include_bytes!("../Cargo.toml");
println!("same length: {}", raw.len() == MANIFEST.len());
}