Rust
Beginner
1 min read
Managing Dependencies in Cargo.toml
Example
# Cargo.toml — real-world dependency configuration
[package]
name = "my_app"
version = "0.2.0"
edition = "2021"
[dependencies]
# Exact caret requirement (^1 means >=1.0.0, <2.0.0)
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# Range requirement
log = ">=0.4, <0.5"
# Git dependency (pinned to a specific commit)
# my_lib = { git = "https://github.com/user/my_lib", rev = "abc1234" }
# Path dependency (local crate)
# utils = { path = "../utils" }
# Optional dependency (activated by a feature flag)
# rayon = { version = "1", optional = true }
[dev-dependencies]
pretty_assertions = "1" # only available in tests
[features]
default = []
# parallel = ["rayon"] # enable with: cargo build --features parallel
# --- src/main.rs ---
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Config {
host: String,
port: u16,
debug: bool,
}
fn main() {
let cfg = Config { host: "localhost".into(), port: 8080, debug: true };
let json = serde_json::to_string_pretty(&cfg).unwrap();
println!("{json}");
let decoded: Config = serde_json::from_str(&json).unwrap();
println!("decoded host: {}", decoded.host);
}