Skip to content

Instantly share code, notes, and snippets.

@max-itzpapalotl
Last active January 12, 2024 11:21
Show Gist options
  • Save max-itzpapalotl/d2247ea6db377786c410755e94a22cf5 to your computer and use it in GitHub Desktop.
Save max-itzpapalotl/d2247ea6db377786c410755e94a22cf5 to your computer and use it in GitHub Desktop.
13. Cargo

13. Cargo

Cargo is the package manager, everybody uses it.

Basic setup for a single executable

cargo new project

Will produce project/Cargo.toml:

[package]
name = "cargo"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

and src/main.rs:

fn main() {
    println!("Hello world!");
}

Basic setup for a library

cargo new --lib projectlib

Will produce projectlib/Cargo.toml:

[package]
name = "cargo"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

and src/lib.rs:

pub fn add(left: usize, right: usize) -> usize {
    left + right
}

Adding dependencies

cargo search sha256
cargo add sha256
cargo add sha256 --features openssl

Documentation here: https://docs.rs/sha256/latest/sha256/

cargo search uuid7
cargo add uuid7

Documentation here: https://docs.rs/uuid7/0.7.2/uuid7/

Using external dependencies

use uuid7::uuid7;

fn main() {
    let u = uuid7();
    println!("{}", u);
    println!("{:?}", u.as_bytes());
}
use uuid7::uuid7;
use sha256::digest;

fn main() {
    let u = uuid7();
    println!("{}", u);
    println!("{:?}", u.as_bytes());

    let d = digest(u.as_bytes());
    println!("{}", d);
}

Building and running

Building:

cargo build 
cargo build --release

Running:

target/debug/cargo
target/release/cargo

Or both:

cargo run 
cargo run --release

Multiple executables

The default binary is rooted at src/main.rs. Put another binary xyz in src/bin/xyz.rs:

In src/bin/xyz.rs:

fn main() {
    println!("Hello world, xyz!");
}

Build with:

cargo build --bin xyz

Run with:

cargo run --bin xyz

All binaries share the same Cargo.toml file. One can configure the path and other stuff like so:

...
[[bin]]
name = "xyz"
path = "abc/src/xyz.rs"
...

then the file must be in abc/src/xyz.rs.

Combined library and executable

With this Cargo.toml:

[package]
name = "project"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[lib]
name = "mylib"
path = "src/mylib/lib.rs"

[dependencies]

And this in src/main.rs:

use mylib::f;

fn main() {
    f();
}

and this in src/mylib/lib.rs:

pub fn f() {
    println!("f");
}

We have both a lib and an executable using the library!

References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment