First step to learn Rust programming

Basic knowledge

  • &str is string literal To do the conversion use the standard String::from(&str) method also can use .to_string()
  • String::from("Something") is string data type
  • enum with structs
 1// Define a tuple struct
 2struct KeyPress(String, char);
 3
 4// Define a classic struct
 5struct MouseClick { x: i64, y: i64 }
 6
 7// Redefine the enum variants to use the data from the new structs
 8// Update the page Load variant to have the boolean type
 9enum WebEvent { WELoad(bool), WEClick(MouseClick), WEKeys(KeyPress) }
10
11let we_load = WebEvent::WELoad(true);

Project manage commands

  • Cargo commands
    • cargo new to create new project
    • cargo build to build a project
    • cargo run to build and run project
    • cargo test Test a project
    • cargo check Check project types
    • cargo doc Build documentation for a project
    • cargo publish Publish a library to crates.io
    • Add dependent crates to a project by adding the crate name to the Cargo.toml file
  • rustup doc open and display the docs about rust

The example of project

  • Directory of project
1mkdir ~/rust-learning-path
2cd ~/rust-learning-path
3mkdir hello-world
4cd hello-world
  • the main.rs
1fn main() {
2	println!("Hello, world!");
3    // Display the message "Hello, world!"
4    todo!("Display the message by using the println!() macro");
5    println!("The first letter of the English alphabet is {} and the last letter is {}.", 'A', 'Z');
6}
  • to build and run the project
1rustc main.rs
2./main

Create a project with Cargo

  • new project
1mkdir rust-learning-path && cd rust-learning-path
2cargo new hello-cargo
3cd hello-cargo
4cargo run

Reference