Use the cargo new command to generate a new binary project or cargo new --lib for a library. This command creates a standard directory structure with a Cargo.toml manifest file and a src/main.rs (or src/lib.rs) entry point, ready for immediate compilation and execution.
For a standard executable project, run the following in your terminal:
cargo new my_cli_tool
cd my_cli_tool
cargo run
This creates a folder named my_cli_tool containing the default structure. The cargo run command compiles the project and executes the resulting binary in one step. If you need to create a library instead of a binary application, add the --lib flag:
cargo new my_shared_lib --lib
cd my_shared_lib
cargo test
This generates a src/lib.rs file instead of src/main.rs. You can verify the project structure and dependencies by inspecting the generated Cargo.toml file, which defines the package metadata and any external crates you might need.
If you want to initialize a new project in the current directory rather than creating a new folder, use the --name flag with cargo init:
cargo init --name existing_project_name
This is useful when you already have a directory with some files and want to add Cargo support without moving anything. Remember that cargo new will fail if the target directory already exists, so ensure the path is empty or use cargo init for existing directories. Once the project is set up, you can manage dependencies by adding lines to the [dependencies] section in Cargo.toml or by running cargo add <crate_name> to automatically update the manifest and lock file.