天天看點

rust 入門筆記:環境安裝、hello World、Cargo

rust 入門

主要參考資料:Rust 程式設計語言

github位址:https://github.com/yunwei37/os-summer-of-code-daily

在linux上面安裝Rust

環境:

uname -a

Linux ubuntu 5.4.0-39-generic #43-Ubuntu SMP Fri Jun 19 10:28:31 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

運作:

curl https://sh.rustup.rs -sSf | sh

Welcome to Rust!

Rust is installed now. Great!

重新開機;

rustc --version

rustc 1.44.1 (c7087fe00 2020-06-17)

很新鮮的樣子

檢視文檔:rustup doc

裝了個插件:Rust support for Visual Studio Code

然後跳了個框,說有些元件還沒裝…

Hello, World!

$ mkdir hello_world

$ cd hello_world

輸入:

fn main() {
    println!("Hello, world!");
}
           
yunwei@ubuntu:~/hello_world$ rustc main.rs
yunwei@ubuntu:~/hello_world$ ./main
Hello, world!
           
  • main 函數是一個特殊的函數:在可執行的 Rust 程式中,它總是最先運作的代碼。它沒有參數也沒有傳回值。
  • rustfmt 的自動格式化工具正在開發中?我等等去看看
  • Rust 要求所有函數體都要用花括号包裹起來。
  • println! 調用了一個 Rust 宏(macro)。
  • 以分号結尾(;),這代表一個表達式的結束和下一個表達式的開始。大部分 Rust 代碼行以分号結尾(看起來不是全部)。

Hello, Cargo!

Cargo 是 Rust 的建構系統和包管理器。

yunwei@ubuntu:~/hello_world$ cargo --version

cargo 1.44.1 (88ba85757 2020-06-11)
yunwei@ubuntu:~$ cargo new hello_cargo
     Created binary (application) `hello_cargo` package
yunwei@ubuntu:~$ cd hello_cargo
           

檔案名: Cargo.toml

[package]
name = "hello_cargo"
version = "0.1.0"
authors = ["yunwei <[email protected]>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

           
  • TOML (Tom’s Obvious, Minimal Language) 格式
  • Cargo 期望源檔案存放在 src 目錄中。項目根目錄隻存放 README、license 資訊、配置檔案和其他跟代碼無關的檔案。使用 Cargo 幫助你保持項目幹淨整潔,一切井井有條。

建構并運作 Cargo 項目

  • cargo build 建構項目:
yunwei@ubuntu:~/hello_cargo$ cargo build
   Compiling hello_cargo v0.1.0 (/home/yunwei/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.72s
           
  • cargo run 在一個指令中同時編譯并運作生成的可執行檔案:
yunwei@ubuntu:~/hello_cargo$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/hello_cargo`
Hello, world!
           
  • cargo check 通常 cargo check 要比 cargo build 快得多,因為它省略了生成可執行檔案的步驟。
yunwei@ubuntu:~/hello_cargo$ cargo check
    Checking hello_cargo v0.1.0 (/home/yunwei/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.11s
           
  • 有别于将建構結果放在與源碼相同的目錄,Cargo 會将其放到 target/debug 目錄。
  • 釋出(release)建構:cargo build --release
Some common cargo commands are (see all commands with --list):
    build       Compile the current package
    check       Analyze the current package and report errors, but don't build object files
    clean       Remove the target directory
    doc         Build this package's and its dependencies' documentation
    new         Create a new cargo package
    init        Create a new cargo package in an existing directory
    run         Run a binary or example of the local package
    test        Run the tests
    bench       Run the benchmarks
    update      Update dependencies listed in Cargo.lock
    search      Search registry for crates
    publish     Package and upload this package to the registry
    install     Install a Rust binary. Default location is $HOME/.cargo/bin
    uninstall   Uninstall a Rust binary
           

編寫 猜猜看 遊戲

  • 為了擷取使用者輸入并列印結果作為輸出,我們需要将 io(輸入/輸出)庫引入目前作用域。
  • 預設情況下,Rust 将 prelude 子產品中少量的類型引入到每個程式的作用域中。如果需要的類型不在 prelude 中,你必須使用 use 語句顯式地将其引入作用域。
  • // 文法開始一個注釋,持續到行尾。
  • 關聯函數

  • 靜态方法

  • & 表示這個參數是一個

    引用

    (reference),它允許多處代碼通路同一處資料,而無需在記憶體中多次拷貝。
  • 使用 Result 類型來處理潛在的錯誤:Result 類型是

    枚舉

    (enumerations),通常也寫作 enums。枚舉類型持有固定集合的值,這些值被稱為枚舉的 成員(variants)。

    Result

    的成員是

    Ok

    Err

  • Cargo.lock 檔案確定建構是可重制的
  • cargo update
yunwei@ubuntu:~/guessing_game$ cargo build
    Blocking waiting for file lock on package cache
           
use rand::Rng;
use std::io;

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(1, 101);

    println!("The secret number is: {}", secret_number);

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read line");

        let guess: u32 = guess.trim().parse().expect("Please type a number!");

        println!("You guessed: {}", guess);

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        }
    }
}