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
$ 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 的成員是 OkErr
  • Cargo.lock 文件確保構建是可重現的
  • cargo update

碰到了這個

yunwei@ubuntu:~/guessing_game$ cargo build
    Blocking waiting for file lock on package cache

解決方法:刪除~/.cargo/.package_cache文件,然後 cargo clean ; cargo build

源代碼:

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;
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章