cargo
Rust Cargo build scripts
Generate a Rust constant before compiling the application. Cargo runs the build script on the host; the generated constant is included by the target source. Example format: rust. Run in a disposable copy of v16/fixtures/projects/build-demo. Expected result (not executed): cargo run --offline --quiet prints Workshop: Ready. Common mistake: Writing generated artifacts into the source directory instead of OUT_DIR.
Formal Syntax & Structure
rust syntaxrust
use std::{env, fs, path::PathBuf};Working Example
Example Snippetrust
use std::{env, fs, path::PathBuf};fn main() { println!("cargo::rerun-if-changed=label.txt"); let label = fs::read_to_string("label.txt").expect("read label"); let out = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR")); fs::write(out.join("label.rs"), format!("const LABEL: &str = {:?};", format!("{}: {}", label_maker::label(), label.trim()))).expect("write generated code");}