Lesson 4 of 50 · rust
Understanding Cargo Projects
Duration: 15 minutes
Lesson 4 of 50 · rust
Duration: 15 minutes
\nmy_project/\n├── Cargo.toml # Project manifest\n├── Cargo.lock # Reproducible builds lock file\n├── src/\n│ ├── main.rs # Binary entry point\n│ ├── lib.rs # Library entry point\n│ └── bin/ # Additional binaries\n├── tests/ # Integration tests\n├── benches/ # Performance benchmarks\n├── examples/ # Example programs\n└── README.md # Documentation\n\n\n## The Cargo.toml Manifest\n\nYour project configuration file:\n\ntoml\n[package]\nname = \"hello_world\"\nversion = \"0.1.0\"\nedition = \"2021\" # 2015, 2018, or 2021\nauthors = [\"Name <email>\"]\ndescription = \"A sample program\"\nlicense = \"MIT\"\n\n[dependencies]\n# Production dependencies\nserde = \"1.0\"\ntokio = { version = \"1.35\", features = [\"full\"] }\n\n[dev-dependencies]\n# Test-only dependencies\nproptest = \"1.0\"\n\n[profile.release]\nopt-level = 3 # Maximum optimization\nlto = true # Link-time optimization\nstrip = true # Strip debug symbols\n\n\n## Crate Types\n\n### Binary Crates (src/main.rs)\n\nProduces executable programs:\n\n\n$ cargo run\n\n\n### Library Crates (src/lib.rs)\n\nProduces reusable code:\n\nrust\n// src/lib.rs\npub fn greet(name: &str) -> String {\n format!(\"Hello, {}!\", name)\n}\n\n\n### Mixed Projects\n\nBoth binary and library in one project:\n\nrust\n// src/lib.rs\npub fn add(a: i32, b: i32) -> i32 { a + b }\n\n// src/main.rs\nuse my_project::add;\nfn main() { println!(\"{}\", add(2, 3)); }\n\n\n## Essential Commands\n\n| Command | Purpose |\n|---------|---------|\n| cargo build | Compile in debug mode |\n| cargo build --release | Compile with optimizations |\n| cargo run | Compile and run |\n| cargo check | Verify without building |\n| cargo test | Run all tests |\n| cargo fmt | Format code |\n| cargo clippy | Lint your code |\n| cargo doc --open | Generate and open docs |\n| cargo clean | Remove build artifacts |\n\n## Managing Dependencies\n\nAdd via command line or edit Cargo.toml:\n\nbash\ncargo add serde\ncargo add --dev proptest\ncargo add tokio --features full\n\n\nVersion specifications:\n\ntoml\nserde = \"1.0\" # Exact version\ntokio = \"~1.35\" # Patch updates only\nchrono = \"^0.4\" # Up to next major version\n\n\n## The Cargo.lock File\n\nLocks dependencies to specific versions for reproducible builds. Commit to version control for binary projects, exclude for libraries.