Rust anatomy: Difference between revisions

From wikinotes
Line 33: Line 33:
== Crates ==
== Crates ==
<blockquote>
<blockquote>
A crate can be either
A crate can be either a library or an executable.
* a library (has <code>src/lib.rs</code> entrypoint)
* an executable (has <code>src/main.rs</code> entrypoint)


If a package only has a single library/executable, the type can be implied from the source files.
<syntaxhighlight lang="bash">
src/lib.rs  # if this exists, crate is a library
src/main.rs  # if this exists, crate is an executable
</source>
You can also specify multiple crates for your package in <code>Cargo.toml</code>.
<syntaxhighlight lang="bash">
# Cargo.toml
[package]
# ...
[[bin]]
name = "foo"  # refers to src/bin/foo.rs
[[bin]]
name = "bar"  # refers to src/bin/bar.rs
[lib]  # <-- single '['s
# refers to 'src/lib.rs', unless 'path' overrides it
</source>
Each of these build targets (lib/bin) is referred to as a '''crate'''.
</blockquote><!-- Crates -->
</blockquote><!-- Crates -->



Revision as of 14:37, 8 February 2023


Project Components

A rust project comprises of

packages build/test/share a collection of crates
crates tree of modules that build a single library, or executable
modules organize scope/privacy of paths
paths files ?

Packages

A package is a collection of crates.

  • it may have multiple executable crates
  • it may only have one library crate
myproject/
  src/
  Cargo.toml
  Cargo.lock

Crates

A crate can be either a library or an executable.

If a package only has a single library/executable, the type can be implied from the source files. <syntaxhighlight lang="bash"> src/lib.rs # if this exists, crate is a library src/main.rs # if this exists, crate is an executable </source>

You can also specify multiple crates for your package in Cargo.toml. <syntaxhighlight lang="bash">

  1. Cargo.toml

[package]

  1. ...

bin name = "foo" # refers to src/bin/foo.rs

bin name = "bar" # refers to src/bin/bar.rs

[lib] # <-- single '['s

  1. refers to 'src/lib.rs', unless 'path' overrides it

</source>

Each of these build targets (lib/bin) is referred to as a crate.

Modules

Modules contain groups of related srcfiles.
modules are private to their parents by default, and public to their child modules.
the name/namespace of the module mirrors it's filesystem location.
the use keyword can merge a module or one of it's elements into the current namespace.

See more details in rust modules.