iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0
佛心分享-SideProject30

網頁遊戲_名字對決系列 第 6

Day6 - 部屬環境 part2 後端-Rust安裝及測試

  • 分享至 

  • xImage
  •  

雖然比較簡陋,但已經有一個前端頁面了,接下來安裝rust試著在網頁上做個小功能吧!
安裝rust:https://www.rust-lang.org/zh-TW/tools/install
rust基礎教學:https://doc.rust-lang.org/book/
我照著上方的教學,安裝完後成功輸出了Hello World
首先新增一個main.rs:

fn main() {
    println!("Hello, world!");
}

cmd中輸入:

> rustc main.rs
> .\main.exe
Hello, world!

其中rustc是Rust的編譯器,執行這個命令後,Rust會檢查剛剛寫的main.rs有沒有語法錯誤,接著將main.rs編譯成電腦看得懂的二進制檔案,最後生成一個main.exe

接著試用官方推薦的Cargo,這是一個Rust的管理&編譯工具,具體這是什麼我也一知半解就不多說了,總之先照著官方教學走,Rust的教學做的很細緻,這也是我選擇從Rust開始學習的原因之一。

cargo new hello_cargo
cd hello_cargo
cargo build

使用cargo new hello_cargo時,會自動生成一個Hello world的main.rs,使用cargo build能像剛剛的rustc一樣編譯main.rs

   Compiling hello_cargo v0.1.0 (D:\program\fight_web_game\backend\hello_cargo)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.44s

編譯時會提示花費的時間,第一次編譯要生成檔案會花比較久,比如我現在花了0.44s
編譯完後可以指定路徑執行,也可以直接使用cargo run執行,使用cargo run會比較方便一點

D:\program\fight_web_game\backend\hello_cargo>.\target\debug\hello_cargo.exe
Hello, world!

D:\program\fight_web_game\backend\hello_cargo>cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s
     Running `target\debug\hello_cargo.exe`
Hello, world!

輸出時不需要花時間再編譯一次,這是因為Cargo可以檢查到檔案沒被更改過,所以不用重新建構就直接執行,如果有更動的話,就需要再編譯一次,比如我修改在Hello, world後面加上一個數字2:

D:\program\fight_web_game\backend\hello_cargo>cargo run
   Compiling hello_cargo v0.1.0 (D:\program\fight_web_game\backend\hello_cargo)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.20s
     Running `target\debug\hello_cargo.exe`
Hello, world2!

使用cargo check的話,可以不編譯,只檢查程式有沒有問題,這樣速度會比較快
比如這樣,檢查只花了0.05s,剛剛的編譯需要0.2s

D:\program\fight_web_game\backend\hello_cargo>cargo check
    Checking hello_cargo v0.1.0 (D:\program\fight_web_game\backend\hello_cargo)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.05s

最後,如果專案都測試完成要發布時,可以使用cargo build --release來最佳化,這樣編譯會更久,但是最終專案的執行速度會更快,很方便的功能。

今天的進度就到這,明天想修改一下前端網頁,新增一個按鈕來測試rust怎麼用在前端上


上一篇
Day5 - 網頁畫面設計3
下一篇
Day7 - 網頁功能製作1
系列文
網頁遊戲_名字對決13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言