1 hello world 的例子可參考 https://kaisery.github.io/trpl-zh-cn/ 及 https://rust-by-example.budshome.com/index.html
2、下面參考 https://www.twle.cn/c/yufei/rust/rust-basic-package-manager.html 試一下
范例: 使用 cargo 創建並構建一個完整的二進制可執行程序項目
參考:https://www.zhihu.com/question/462461906/answer/1915949373
https://doc.rust-lang.org/cargo/commands/cargo-install.html
https://rust-by-example.budshome.com/index.html
https://kaisery.github.io/trpl-zh-cn/
1 (win10系統) 在某個目錄下執行: cargo new guess-game-app
提示 Created binary (application) `guess-game-app` package 說明項目創建成功
2 打開 https://crates.io/ 找第三方庫或 crates ,
輸入 rand 搜索,結果中排第一位的是:rand v0.8.4
3 修改剛才創建的guess-game-app目錄下的Cargo.toml ,在[dependencies]
節中添加 rand = "0.8.4"
。
4 輸入 cargo build
來預編譯項目
顯示:warning: spurious network error (2 tries remaining): failed to send request: 操作超時
5 參考 https://www.cnblogs.com/fifolilo/p/13184622.html Win10 修改 rust 的 crates 源為中科大源
在 C:\Users\你的用戶名\.cargo 下,新建 config
文件(注意沒有擴展名),並編輯內容如下:
[http] check-revoke = false [source.crates-io] replace-with = 'ustc' [source.ustc] registry = "https://mirrors.ustc.edu.cn/crates.io-index"
6 再次執行 cargo build
安裝依賴 成功
7 修改 guess-game-app\src\main.rs 內容如下:
use std::io; extern crate rand; // 導入當前項目下的 rand 第三方庫 use rand::random; fn get_guess() -> u8 { loop { println!("Input guess") ; let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("could not read from stdin"); match guess.trim().parse::<u8>(){ // 需要去除輸入首尾的空白 Ok(v) => return v, Err(e) => println!("could not understand input {}",e) } } } fn handle_guess(guess:u8,correct:u8)-> bool { if guess < correct { println!("Too low"); false } else if guess> correct { println!("Too high"); false } else { println!("You go it .."); true } } fn main() { println!("Welcome to no guessing game"); let correct:u8 = random(); println!("correct value is {}",correct); loop { let guess = get_guess(); if handle_guess(guess,correct){ break; } } }
8 在 終端 中輸入命令 cargo run
編譯並運行我們的猜數字游戲
看了一下,第三方庫也下載到了 C:\Users\你的用戶名\.cargo 目錄下