Python与Rust语法比较
可以复制粘贴本文代码:
- 在https://play.rust-lang.org/ 运行 Python
- 在https://repl.it/languages/python3 中运行 Rust 示例
安装新的库/包
Python
$ pip install foo
Rust
$ cargo install foo
运行编译:
Python
$ python my_python_program.py
Rust
$ cargo run
在 Rust 中,有一个 --release 标志可以在编译时进行更多优化,但编译时间会更长。
$ cargo run --release
你好世界
Hello World
Python
if __name__ == "__main__": |
Rust
fn main() { |
类型和声明
创建新对象、基本原始类型值和数据结构。
Python
age = 80 |
Rust
use std::collections::HashMap; |
定义一个函数
定义一个接收 2 个整数参数并返回其和的函数。
Python
def add(a, b): |
带有类型注释的 Python
它看起来更类似于 Rust。
def add(a: int, b: int) -> int: |
Rust
/// Adds a to b |
列表/切片
创建列表、添加新元素、获取列表长度、按索引分片、使用 for 循环迭代以及使用枚举器迭代。
Python
names = ['bugs', 'taz', 'tweety'] |
Rust
fn main() { |
.step_by() 相当于 python 的 range/xrange 步长参数。
python:
for i in range(0,10,2): |
rust:
for i in (0..10).step_by(2) { |
字典/地图
创建新字典(哈希映射)、添加新键和值、更改值、通过键获取、检查键是否包含等。
Python
创建新二进制文件并填充 |
Rust代码
use std::iter::FromIterator; |
在 Rust 中用 Pythonic 替代 dict/map
你可以使用 maplit crate 来加载 hashmap! 宏,以获得高效的糖化(又称 Pythonic)语法!
# Cargo.toml |
#[macro_use] extern crate maplit; |
集合/哈希集
创建集合(由唯一键组成的哈希值),添加新键并计算交集、差集和合集
Python
# 创建和填充 |
或使用 maplit crate 进行语法润色
#[macro_use] extern crate maplit; |
While 和 For 循环
循环,直到满足某个条件或遍历一个可迭代对象。
Python
# While loop |
Rust
fn main() { |
Rust 具有 Python 所没有的循环功能:Loop Labels循环标签
'outer: for x in 0..10 { |
文件
读取文本文件并逐行打印内容,最后正确关闭文件。
Python
from pathlib import Path |
Rust
use std::io::{BufReader, BufRead}; |
异常/返回错误
期望出现异常并识别错误。
Python
def div(a, b): |
Rust
fn div(a: i32, b: i32) -> Result<i32, &'static str> { |
并发性
Python
thr = Thread(target=add, args=(1, 2), daemon=True) |
Rust
use std::thread; |
线程间通信
管理线程之间的数据上下文。
Python
from queue import Queue |
Rust
use std::thread; |
排序
对列表进行排序、反转和使用按键。
Python
names = ['taz', 'bugs', 'daffy'] |
Rust
fn main() { |
带有 Flask / Rocket 的 Web 应用程序
Python
from flask import Flask |
Rust
#![feature(plugin)] |
具有错误处理功能的 HTTP 请求
Python使用 requests
import requests |
Rust使用reqwest
extern crate reqwest; |
多线程HTTP爬虫
使用requests
from concurrent.futures import ThreadPoolExecutor |
Rust使用reqwest
extern crate reqwest; |
JSON 编码和解码
Python
import json |
Rust
extern crate serde; |
面向对象
Python:
class Cat: |
Rust
struct Cat { |
注意:在 Rust 中,最好避免使用字符串类型的 API,因此在上面的示例中,我们最好让 garfield = Cat::new("Garfield") 并接受 Cat 的实例作为其他参数。
打印调试/日志对象
打印格式化对象调试信息
Python
class Actor: |
Rust
#[derive(Debug)] |