Published Crates
Several approaches to creating a “Hello, World” application have been shown. Next, we will create a variation of the “Hello, World” application using a published crate. Rustascii is a public crate found in crates.io and displays various ASCII art for Rust, such as the Rust logo. The display_rust_ascii function of this crate displays “Hello, Rustaceans!” Here is the result of the function:
____ __ / __ \__ _______/ /_ / /_/ / / / / ___/ __/ / _, _/ /_/ (__ ) /_ /_/ |_|\__,_/____/\__/ Hello, Rustaceans!
You must first locate the rustascii crate in the crates.io repository. Fortunately, crates.io has a search feature at the top of the page. Searching for rustascii will locate the latest version of the crate. When the crate is found, a brief description, current version number, and other helpful information about the published crate are provided, as shown in Figure 2.3.
Figure 2.3 The rustascii crate in the crates.io repository
In a package using an external crate, you need to update cargo.toml to reference the crate. You should enter the name and version of the crate in the dependencies section. Find the icon for a clipboard within the rustascii page in crates.io. Select the clipboard to copy the dependency information identifying the current version of the rustascii crate. Finally, paste that information into the dependencies section of the cargo.toml file, as highlighted in Listing 2.11.
Code Listing 2.11. Cargo.toml file that includes a rustascii dependency
[package] name = "use_rust_ascii" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/ manifest.html [dependencies] rustascii = "0.1.1"
After updating the cargo.toml file, call the display_rust_ascii function in the rustascii crate using the :: operator. The syntax is crate::function. Listing 2.12 shows sample code in an executable crate.
Code Listing 2.12. Displaying “Rust” in ASCII art
fn main() { rustascii::display_rust_ascii(); }
When executed, this crate calls the display_rust_ascii function in the rustascii crate to display the greeting.