Ubuntu巡航记(4) -- Rust 安装

前言

Rust 是一个现代版的 C/C++ 程序语言,它加入物件导向、套件安装(cargo)、函数式程序设计(Functional Programming)、WebAssembly...等等的设计模式与观念,同时改善C最致命的缺点 -- 记忆体泄漏(Memory Leak),是一个值得投资的语言。

另外,也可以与Python整合,弥补Python直译器不能建置为执行档的缺憾,既可以加速执行的速度,程序码又可以免於公开。

Rust 安装

安装程序非常简单,只要两步骤:

  1. 下载且安装:
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    按 Enter 即可。

  2. 验证:
    rustc --version

  3. 建立 C 相关环境:
    sudo apt install build-essential

写一支 Rust 程序

  1. 建立专案,不要用大写:
cargo new hello_world
  1. 编译专案:
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:.

Python 与 Rust 整合

请参阅『Rust Inside Other Languages』说明,

  1. 建立专案,不要用大写:
cargo new embed
  1. src/main.rs改名为lib.rs,程序码如下,主要是产生10个执行緖,每个执行緖累加0至5百万:
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!");
}
  1. 修改 Cargo.toml,在档案尾巴加入以下设定:
[lib]
name = "embed"
crate-type = ["dylib"]
  1. 建置专案:
cargo build --release

产生函数库 target/release/libembed.so。

  1. 新增 Python 档案 embed.py,程序码如下:
from ctypes import cdll

# linux
lib = cdll.LoadLibrary("target/release/libembed.so")

# Windows
#lib = cdll.LoadLibrary("target/release/embed.dll")

lib.process()

print("done!")
  1. 测试,以 Python 呼叫 Rust:
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 !!


<<:  Vue3 ( CLI + github ) -4

>>:  Node-RED学习心得(实战篇1)

[Day 4] lock-free and CAS

前言 昨天聊到原子操作时提到了2个名词, 有些人可能不熟, 会在今天简单说明。明天会有相应的实作。 ...

D22 - 彭彭的课程# Python 乱数与统计模组(2)

天啦居然已经22天了 时间不知不觉过很快 又要迎接双十连假@@? 先预祝大家连假愉快 每次遇到这种时...

[Day 13]每天前进一点应该也是进步吧?(前端篇)

挑战目标: MockNative Camp 今天我们来整理昨天没有弄好的footer右边的部分, 这...

Day02-容器化管理工具(Docker)

前言 今天就要正式进入 DevOps 的环节了,首先要来介绍的是 Docker,之所以要先介绍 D...

学习书单与资源

如果你还在个人修炼的阶段,有几本我认为是经典的书籍很推荐你尽早阅读,吸收消化成为自己的东西。 1.&...