Rust筆記

出自Tan Kian-ting的維基
於 2024年3月16日 (六) 11:37 由 Tankianting討論 | 貢獻 所做的修訂 →‎印出當前目錄(current directory)
跳至導覽 跳至搜尋

Programming Rust筆記

Ch1概論

  • 系統程式語言有「未定義行為」。
  • 使用者輸入的內容可能會導致程式漏洞。
    • 編譯時消除未定義行為
    • 安全,亦於使用
    • 平行編譯
    • 0 overhead的C++,只有必要花費,不會花費太多資源消耗
    • 善用底層
    • cargo、trait、generic

Ch2 Rust特性簡單導覽

  • rust doc產生文件
  • rust編譯器
  • cargo編譯管理器
    • cargo clean清除編譯文件


沒有;結尾的視為回傳值。

  • 函數定義示例:
fn foo(mut n :i64) -> i64{
...
}

assert!(a == b)錯誤時拋出panic


  • identifier後面的!為巨集
  • let x = m可以這樣寫,會儘可能型別推論。比較let x : i64 = m

其他

型別

函數

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]")

變數

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

字串

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

Gtk4

  1. Grid於Rust的Gtk4 binding