以语法对照表格形式学习新语言,以rust为例。
加上基础api
c | rust | |
---|---|---|
链接 | https://www.runoob.com/cprogramming/c-tutorial.html | https://www.runoob.com/rust/rust-tutorial.html |
https://www.runoob.com/cplusplus/cpp-tutorial.html | ||
在线工具 | https://www.runoob.com/try/runcode.php?filename=helloworld&type=c | https://play.rust-lang.org/?version=stable&mode=debug&edition=2021 |
rust编译器依赖于c编译器 | ||
注释 | // or /* */ | // or /* */ |
行结尾 | ; | ; |
路径分隔符 | / or \ | :: |
代码块 | {} | {} |
函数体表达式 | 无 | {} |
大小写 | 区分 | |
标识符 | 以字母 A-Z 或 a-z 或下划线 _ 开始,后跟零个或多个字母、下划线和数字(0-9)。 | |
关键字 | https://www.runoob.com/cprogramming/c-basic-syntax.html | |
c89 keys | auto,break,case,char,const,continue,default,do,double, | |
else,enum,extern,float,for,goto,if,int,long,register,return,short, | ||
signed,sizeof,static,struct,switch,typedef,unsigned,union,void,volatile,while | ||
c99 keys | _Bool,_Complex,_Imaginary,inline,restrict | |
c11 keys | _Alignas,_Alignof,_Atomic,_Generic,_Noreturn,_Static_assert,_Thread_local | |
数据类型 | void,char,unsigned char,signed char ,int,unsigned int,short,unsigned short,long,unsigned long | i8,u8,i16,u16,i32,u32,i64,u64,i128,u128,isize,usize |
float,double,long double | f32,f64,f128 | |
_Bool | bool | |
unicode | 无 | char(4byte)建议utf8 |
字符串 | char str[] = “RUNOOB”; | let str = String::from(“RUNOOB”); |
字符串切片 | 自行实现 | let part1 = &str[0…5];//类似string_view |
非字符串切片 | 自行实现 | let part = &arr[0…3]; |
变量 | int i=0; | let i:i32 = 0; |
变量声明 | extern int i; | |
重影(Shadowing) | 无 | let x = 5; let x = x + 1; |
左值 | 指向内存位置的表达式 | |
右值 | 存储在内存中某些地址的数值 | |
常量 | long myLong = 100000L;float myFloat = 3.14f;char myChar = ‘a’;char myString[] = “Hello, world!”; | |
#define PI 3.14159 | ||
const int MAX_VALUE = 100; | ||
存储类型 | auto,register,static,extern | |
所有权 | 无 | 每个值都有一个变量,称为其所有者。一次只能有一个所有者。当所有者不在程序运行范围时,该值将被删除。 |
移动(Move) | 无 | let s1 = String::from(“hello”);let s2 = s1; println!(“{}, world!”, s1); // 错误!s1 已经失效 |
克隆(Clone) | 无 | let s1 = String::from(“hello”);let s2 = s1.clone(); println!(“{}, world!”, s1); |
算术运算符 | ±*/% ++ – | |
关系运算符 | == != > < >= <= | |
逻辑运算符 | && || ! | |
位运算符 | & | ^ ~ << >> | |
赋值运算符 | = += -= *= /= %= &= |= ^= <<= >>= | |
三元运算符 | (a > 0)? 1:-1 | if (a > 0) { 1 } else { -1 } |
杂项运算符 | sizeof() & * ?: | |
运算符优先级 | https://www.runoob.com/cprogramming/c-operators.html | |
判断/条件语句 | if(…){…}else{…} | if(…){…}else{…} 可以不要(),仅支持bool判断 |
switch分支判断 | switch(…){case …:break;case …:break;default:…;} | 无,用match替代 |
if let | 无,用if替代 | if let 0 = i {println!(“zero”);}else{…} |
循环 | for(;; ){} while(){} do{}while(); | while(){} for i in a.iter(){…} loop{… break; …} |
break,continue,goto | ||
函数定义 | int max(int x, int y) {…} | fn max(x: i32, y: i32)->i32 {…} |
函数嵌套 | 无 | fn main() { fn five() -> i32 {5}} |
函数调用 | int ret = max(a, b); | |
参数作用域 | 全局变量,局部变量,形式参数为局部变量 | |
可变参数 | … 具体示例见printf实现 | |
数组 | int i_array[] = {1, 2, 3, 4, 5}; | let mut i_array: [i32; 5] = [1, 2, 3, 4, 5]; |
数组下标 | >=0 | |
数组访问 | i_array[i] | i_array[i] |
多维数组 | int i_a2[3][3]; | |
动态数组 | 通过指针和malloc实现 | |
指针 | int *p=NULL; | 无 |
引用 | 无 | let s1 = String::from(“hello”);let s2 = &s1; |
可变引用 | 无 | let mut s1 = String::from(“run”);let s2 = &mut s1; |
垂悬引用 | 无 | 编译期识别,eg:fn dangle() -> &String { let s = String::from(“hello”); &s} |
地址 | 取地址方式&t | |
函数指针 | typedef int (*fun_ptr)(int,int); | |
枚举 | enum DAY{ MON=1, TUE, WED, THU, FRI, SAT, SUN}; | enum Book {Papery, Electronic} enum Book { Papery(u32), Electronic(String),} |
枚举赋值 | 无 | enum Book {Papery { index: u32 },Electronic { url: String },} let book = Book::Papery{index: 1001}; |
match | 无,类似switch | match book {Book::Papery { index } => { println!(“Papery book {}”, index); }, Book::Electronic { url } => { println!(“E-book {}”, url); }} |
NULL | NULL==0 | 无 |
Option枚举 | 无 | 替代NULL。enum Option< T > {Some(T), None,} |
let opt: Option<&str> = Option::None;match opt {Option::Some(something) => { println!(“{}”, something);}, Option::None => { println!(“opt is nothing”); }} | ||
结构体 | struct SIMPLE{ int a; char b; double c;}; | struct SIMPLE{ a:i32; b:i8; c:f64;} |
复合类型/元组 | 无 | let tup: (i32, f64, u8) = (500, 6.4, 1);let (x, y, z) = tup; |
元组结构体 | 无 | struct Color(u8, u8, u8);let black = Color(0, 0, 0); |
单元结构体 | 无 | struct UnitStruct;//无成员 |
结构体成员访问 | . 或 -> | |
结构体方法 | 无 | struct Rectangle { width: u32, height: u32,} impl Rectangle { fn area(&self) -> u32 {self.width * self.height}} |
结构体关联函数 | 无 | impl Rectangle { fn create(width: u32, height: u32) -> Rectangle { Rectangle { width, height } }} //impl 可以写多次 |
输出结构体 | 无 | println!(“rect1 is {:?}”, rect1);//属性较多的话可以使用另一个占位符 {:#?} |
共用体 | union Data{ int i; float f; char str[20];}; | |
共用体成员访问 | 同结构体 | |
位域 | struct bs{ int a:8; int b:2; int c:6;}; | |
位域成员访问 | 同结构体 | |
别名 | typedef unsigned char BYTE; | |
程序入口 | int main( int argc, char *argv[] ) | |
输入 | int scanf(const char *format, …) 函数从标准输入流 stdin 读取输入 | |
输出 | int printf(const char *format, …) 函数把输出写入到标准输出流 stdout | |
文件读写 | FILE *fopen( const char *filename, const char *mode ); int fclose( FILE *fp );int fputs( const char *s, FILE *fp );char *fgets( char *buf, int n, FILE *fp );fread(…)fwrite(…)… | |
预处理 | #define #include #undef #ifdef #ifndef #if #else #elif #endif #error #pragma | |
预定义宏 | __DATE__ __TIME__ __FILE__ __LINE__ __STDC__ | |
预处理器运算符 | \ # ## | |
宏带参数 | #define square(x) ((x) * (x)) | |
头文件 | #include <stdio.h> #include “my_head.h” | |
类型转换 | int i=3;double d = (double)i; | |
错误处理 | extern int errno ;fprintf(stderr, “错误号: %d\n”, errno); perror(“通过 perror 输出错误”); fprintf(stderr, “错误号对应的描述: %s\n”, strerror( errno )); | 可恢复错误用 Result<T, E> 类来处理,对于不可恢复错误使用 panic! 宏来处理。支持回溯。 |
回溯 | 非自带 | 支持。run with RUST_BACKTRACE=1 environment variable to display a backtrace. |
Result<T, E> | 用int自行实现 | enum Result<T, E> { Ok(T), Err(E),} 在 Rust 标准库中可能产生异常的函数的返回值都是 Result 类型的。 |
?符号 | 无 | ? 符仅用于返回值类型为 Result<T, E> 的函数 |
unwrap,expect | 无 | 可恢复错误按不可恢复错误处理 |
除0 | 异常 | |
程序退出状态 | exit(EXIT_SUCCESS); 0为正常状态。EXIT_FAILURE==-1 | |
递归 | 一般通过递归函数实现 | |
内存管理 | malloc free | |
命令行参数 | int main( int argc, char *argv[] ) | |
随机数 | srand(time(0)) rand() | |
排序 | void qsort(void *b, size_t n, size_t s, compar_fn cmp); | |
查找 | void *bsearch (const void *__key, const void *__base, size_t __nmemb, size_t __size, __compar_fn_t __compar); | |
组织管理 | .h.c.lib.dll … | 箱(Crate)、包(Package)、模块(Module) |
访问权 | 无 | 公共(public)和私有(private),默认私有,eg: pub mod government { pub fn govern() {} } |
模块(Module) | 无,有点像cpp的namespace | mod nation {mod government {fn govern() {}} mod congress {fn legislate() {}} mod court {fn judicial() {}}} |
模块自描述 | 无 | pub fn message() -> String { String::from(“This is the 2nd module.”)}// second_module.rs文件头 |
路径 | 无 | 绝对路径从 crate 关键字开始描述。相对路径从 self 或 super 关键字或一个标识符开始描述。 |
use | 无 | use crate::nation::government::govern as nation_govern; |
泛型函数 | _Generic | fn max< T >(array: &[T]) -> T {…} |
泛型结构 | 无 | struct Point< T > {x: T, y: T} |
特性(trait) | 无 | trait Descriptive { fn describe(&self) -> String;} impl < 特性名 > for < 所实现的类型名 > |
接口(Interface) | 无 | trait类似,但可以定义默认实现 |
代码例子 | https://www.runoob.com/cprogramming/c-examples.html | |
标准库 | stdio.h … https://www.runoob.com/cprogramming/c-standard-library.html | https://doc.rust-lang.org/stable/std/all.html |