Templates
Generated Rust project layouts: the crates, modules and configuration cargo new does not create.
cargo new creates a package containing a
Cargo.toml,
a .gitignore and one source file. --bin writes a main that prints
Hello, world!; --lib writes an add function and a unit test. There are no
other variants, and the two cannot be combined.
Everything past that is set up by hand: further crates and the dependencies between them, a workspace manifest, modules and their declarations, third-party dependencies and the code that initialises them.
The templates here generate that setup. Each one is a project layout with the structure and configuration already in place, and a single worked example of whatever the template covers. What a template covers varies:
- a console crate and a library crate in one workspace, with the path dependency and the call between them written
- a module containing code, declared and wired into the crate around it
- a web API with a route, a handler and server startup, so the generated project can be run and the endpoint called
- logging configured and initialised, so a log statement compiles and outputs without further setup
The example code is meant to be replaced. Deleting the bodies leaves the structure, which is the part being generated.
Templates are generated with cargo-generate, a cargo subcommand. It copies the template, substitutes the names given on the command line, and writes the project. Names not given are derived from the project name.
Installing cargo-generate
cargo-generate is a separate subcommand, installed once.
cargo install cargo-generate
The templates
One page each: what it generates, and the command.
A shorter command
A favourite in $CARGO_HOME/cargo-generate.toml maps a name to the repository and subfolder, replacing the URL on the command line.
[favorites.cli_lib]
git = "https://github.com/NGDeveloper125/rusty-yellow-pages-templates"
subfolder = "cli_lib"
After that
cargo generate cli_lib --name inventory_tool