Install Rust
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
Hello World Example
vi main.rs
fn main() { println!("Hello, world!"); }
Compile
rustc ./main.rs
Run
./main
Hello, world!
Using the Package Manager
Create a project using Cargo
cargo new hello_cargo
Creating binary (application) `hello_cargo` package note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
This command creates a folder with the name of the new project containing a src directory and the dependency file called Cargo.toml.
hello_cargo ├── .git │ ├── HEAD │ ├── config │ ├── description │ ├── hooks │ │ └── README.sample │ ├── info │ │ └── exclude │ ├── objects │ │ ├── info │ │ └── pack │ └── refs │ ├── heads │ └── tags ├── .gitignore ├── Cargo.toml └── src └── main.rs
It has also initialized a new Git repository along with a .gitignore file. Git files won’t be generated if you run cargo new
within an existing Git repository; you can override this behavior by using cargo new --vcs=git
.
Cargo.toml
[package] name = "hello_cargo" version = "0.1.0" edition = "2021" [dependencies]
Building
cargo build
Build and Run
cargo run
Build for Release
cargo build --release
This command will create an executable in target/release instead of target/debug. The optimizations make your Rust code run faster, but turning them on lengthens the time it takes for your program to compile. This is why there are two different profiles: one for development, when you want to rebuild quickly and often, and another for building the final program you’ll give to a user that won’t be rebuilt repeatedly and that will run as fast as possible. If you’re benchmarking your code’s running time, be sure to run
cargo build --release
and benchmark with the executable in target/release.
References
Reference | URL |
---|---|
The Rust Programming Language | https://doc.rust-lang.org/book/title-page.html |