{
"$type": "site.standard.document",
"bskyPostRef": {
"cid": "bafyreifs6m7kww3oho75heurjoq2qzjgiginrmyhjmb5l5pumj3gzypeku",
"uri": "at://did:plc:ivbknywyskln22er3nkssdhl/app.bsky.feed.post/3mg3xybolj642"
},
"path": "/t/alternative-to-cargo-new-templates-examples-as-build-target-templates/24047#post_2",
"publishedAt": "2026-03-02T16:13:39.000Z",
"site": "https://internals.rust-lang.org",
"tags": [
"PackageIdSpec",
"crates.io",
"t-cargo > Making alternative registries nicer to use @"
],
"textContent": "One option could be:\n\n\n $ cargo new --bin --from clap\n ... list all examples ...\n $ cargo new --bin --from clap demo\n\n\nwould create\n\n`Cargo.toml`:\n\n\n ...\n\n [dependencies]\n clap = { version = \"4.5.30\", features = [\"derive\" }\n\n\n`src/main.rs`:\n\n\n use clap::Parser;\n\n /// Simple program to greet a person\n #[derive(Parser, Debug)]\n #[command(version, about, long_about = None)]\n struct Args {\n /// Name of the person to greet\n #[arg(short, long)]\n name: String,\n\n /// Number of times to greet\n #[arg(short, long, default_value_t = 1)]\n count: u8,\n }\n\n fn main() {\n let args = Args::parse();\n\n for _ in 0..args.count {\n println!(\"Hello {}!\", args.name);\n }\n }\n\n\nThere are several routes we can take for copying the example:\n\n * If its `examples/foo.rs`, copy that in. If its a `examples/foo/main.rs` then copy it to `main.rs`, `lib.rs`, or `mod.rs` along with the rest of the directory\n * Apparently, cargo doesn't discover `examples/foo/lib.rs` though lib examples are supported by setting `crate-types` in `Cargo.toml`\n * Should we limit lib examples to only being used for mods and `lib.rs`? Or do we auto-append `fn main()`?\n * Should we limit bin examples to `main.rs`, tests, and build scripts? Or copy them, over and have `main.rs` be dead code?\n\n\n\nFor mods, maybe this would be:\n\n\n $ cargo new --mod src/foo --from clap demo\n\n\nIf the mod exists, it will be used as the parent for the new mod. If it isn't, then it will be used.\n\nFor Cargo script, it would be:\n\n\n $ cargo new --file --from clap demo\n\n\nwhere it defaults the filename to the example name if a path isn't given.\n\nThoughts:\n\n * Not thrilled with multi-valued flags\n * We could accept a PackageIdSpec for non-dependency packages\n * Full-form is verbose and hard to write out (`registry+https://github.com/rust-lang/crates.io-index#clap@4.5.56`)\n * If we support short form (`clap`, `clap@4.5.56`), we could get some dependency confusion going on (thought you were adding an example from a package in a local dependency that points to git or an alt registry but instead get from crates.io. If we support a default registry in `Cargo.toml` as suggested at #t-cargo > Making alternative registries nicer to use @ , then this might limit the impact but not remove it.\n\n",
"title": "Alternative to `cargo new` templates: examples as build-target templates"
}