Recently, I learned basic of Rust. I follow the official documentation. This tutorial is based on official book documentation.
Getting Started#
Hello world#
- Install latest stable version using
dustup
- Compile using rustc
- Formatter using rustfmt
- Method with ! In the end will call macro
Hello, Cargo!#
- Cargo: build system and package manager that handle dependencies.
- Create project with cargo using
cargo new package_name
- In the project there will be
Cargo.toml src
- TOML: Tom’s Obvious, Minimal Language
- Cargo.toml is the project configuration.
- In src folder, it’s contains main.rs
- To build project using
cargo build
. - To build and run,
cargo run
— it’s most used command. - To build project without producing a binary using
cargo check
. - To release project using `cargo build —release
Programming a guessing game#
use std::io
to retrieve user input and print the result as output.- By default variable is immutable by default — once it has value, the value won’t change.
# immutable
let apples = 5
# to mutable
let mut bananas = 5;
- Create new string with
String::new()
. io::stdin().read_line( )
to read user input.&
indicates reference — don’t need to copy the data into memory multiple times.- Handling exception with
.except
Result
is enumeration ofOk
andErr
— if Ok then the operation was successful, and inside Ok is the generated value. The Err variant means the operationn failed, and Err contains imformation about how or why the operation failed.- Printing variable using println with
{}
or{variable_name}
. - Crate is a collection of source code — the project is called binary crate whichh is an executable.
- Library crate one of them is
rand
— for get random number. - Add
rand
to Cargo.toml dependencies list. break;
to quit loopcontinue;
to next iteration in loopmatch
is a expression that can be use for error handling, ok and err.
Here's the code and the output of the guessing game program: