Rust - Getting Started
Installing Rust on MacOs
Rustup: the Rust installer and version management tool.
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Project and Package Manage
Cargo: the Rust build tool and package manager.
Like Maven for Java.
- build your project with cargo build
- run your project with cargo run
- test your project with cargo test
- build documentation for your project with cargo doc
- publish a library to crates.io with cargo publish
Hello Rust
Use cargo to create a project very easily.
$ cargo new hello-rust
This will generate a new directory called hello-rust with the following files:
hello-rust
|- Cargo.toml
|- src
|- main.rs
Cargo.toml is the manifest file for Rust. It’s just like pom.xml for Maven project.
src/main.rs is where we’ll write our application code.
Run this cargo project by using following command:
$ cargo run
Compiling hello-rust v0.1.0 (/Users/ag_dubs/rust/hello-rust)
Finished dev [unoptimized + debuginfo] target(s) in 1.34s
Running `target/debug/hello-rust`
Hello, world!
A simple application with dependency
In this project, we’ll use a crate called ferris-says.
In our Cargo.toml file we’ll add this information (that we got from the crate page):
[dependencies]
ferris-says = "0.1"
Now let’s write a small application with our new dependency. In our main.rs, add the following code:
use ferris_says::say; // from the previous step
use std::io::{stdout, BufWriter};
fn main() {
let stdout = stdout();
let out = b"Hello fellow Rustaceans!";
let width = 24;
let mut writer = BufWriter::new(stdout.lock());
say(out, width, &mut writer).unwrap();
}
Then run the application:
$ cargo run
The output is:
----------------------------
| Hello fellow Rustaceans! |
----------------------------
\
\
_~^~^~_
\) / o o \ (/
'_ - _'
/ '-----' \