Rust筆記

出自Tan Kian-ting的維基
跳至導覽 跳至搜尋

Programming Rust筆記

參見:Programming Rust筆記

其他

套件管理

cargo

加入新函式庫

cargo add csv

編輯器

Emacs

  • rust-mode
    • C-c C-c C-r:跑程式
    • C-c C-f:改善排版,要先裝rustfmt

型別

函數

struct

struct Aminal {
    species: String,
    name: String,
    weight: u64,
}


資料結構

函數

  1. 得到 UTF-8 字串長度的方法:UnicodeSegmentation::graphemes(參見:Stack Overflow
  2. 匯入外部函式庫

印出當前目錄(current directory)

use std::env;
...
    println!("{:?}", env::current_dir());

執行結果: Ok("[project_dir]")

sysargv 傳入程式的引數

求出引數個數長度,沒輸入自定引數則為0:

use std::env;
...
    println!("{}", env::args().len());

變數

  1. 使用參照的方法
    foo (x : &mut i64){...}
  2. 連結字串
    let concat_str = format!("{}{}", str1, str2);

字串

  1. 獲得子字串:a = a[..1].to_string();

食譜 (Cookbook)

子目錄的item用for遍歷,轉成字串

    let corpus_CSV_paths = fs::read_dir("./corpus").unwrap();
    for path in corpus_CSV_paths {
       let path_string = format!("{:?}", path.unwrap().path());
    }

讀檔案顯示資料

摘自:https://doc.rust-lang.org/book/ch12-02-reading-a-file.html

let contents = fs::read_to_string(file_path)
        .expect("Should have been able to read the file");

    println!("With text:\n{contents}");

函式庫

Gtk4

  1. Grid於Rust的Gtk4 binding