Rust 是一個現代版的 C/C++ 程式語言,它加入物件導向、套件安裝(cargo)、函數式程式設計(Functional Programming)、WebAssembly...等等的設計模式與觀念,同時改善C最致命的缺點 -- 記憶體洩漏(Memory Leak),是一個值得投資的語言。
另外,也可以與Python整合,彌補Python直譯器不能建置為執行檔的缺憾,既可以加速執行的速度,程式碼又可以免於公開。
安裝程序非常簡單,只要兩步驟:
下載且安裝:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
按 Enter 即可。
驗證:
rustc --version
建立 C 相關環境:
sudo apt install build-essential
cargo new hello_world
cd hello_world
# 編譯
cargo build
# 執行
cargo run
顯示 Hello, world!
可修改 src/main.rs 程式。
也可以編譯 main.rs,成為執行檔:
rustc main.rs
之後就可以執行,不可以在檔案管理員 double click,因為目前路徑不在預設搜尋路徑中:
./main
可以修改登入檔(gedit ~/.bashrc),加入目前路徑在預設搜尋路徑中:
export PATH=$PATH:.
請參閱『Rust Inside Other Languages』說明,
cargo new embed
use std::thread;
#[no_mangle]
pub extern fn process() {
let handles: Vec<_> = (0..10).map(|_| {
thread::spawn(|| {
let mut x = 0;
for _ in 0..5000000 {
x += 1
}
x
})
}).collect();
for h in handles {
println!("Thread finished with count={}",
h.join().map_err(|_| "Could not join a thread!").unwrap());
}
println!("Rust done!");
}
[lib]
name = "embed"
crate-type = ["dylib"]
cargo build --release
產生函數庫 target/release/libembed.so。
from ctypes import cdll
# linux
lib = cdll.LoadLibrary("target/release/libembed.so")
# Windows
#lib = cdll.LoadLibrary("target/release/embed.dll")
lib.process()
print("done!")
python embed.py
輸出如下:
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Rust done!
done!
勝利成功,Happy Coding !!