站群系列服務(wù)器做視頻網(wǎng)站互聯(lián)網(wǎng)營銷外包推廣
以語法對照表格形式學(xué)習(xí)新語言,以rust為例。
關(guān)于rust的個人看法:
- 能否替代c?部分場景可以,長遠(yuǎn)看并不會。如果c再擴(kuò)一些關(guān)鍵字,類似cpp的吸星大法式擴(kuò)充,rust并不具備優(yōu)勢。
- 解決了c的內(nèi)存管理問題?部分解決。所有權(quán)概念是將c中內(nèi)存管理模式加了約束,并在編譯期做了檢查。
- 關(guān)于語言的生態(tài)位,個人感覺rust很難替代c的生態(tài)位。rust似乎是科研人員對c等語言進(jìn)行研究后,加入了一些新的,實際上已有的概念。往往是編程實踐中的范式,做了語言層面的語法支持。類似openmp擴(kuò)展。
- 語言本質(zhì)上逃不脫圖靈機(jī)的定義,在最小實現(xiàn)基礎(chǔ)上,為了方便、安全、開發(fā)效率等,加了編程范式的語法支持。
- c、cpp語言已經(jīng)做得夠好,設(shè)計哲學(xué)也是效率至上,安全問題交給開發(fā)者負(fù)責(zé)。rust引入的所有權(quán)概念,在c、cpp中實際也可以用編程范式(智能指針)實現(xiàn)。
- AI時代是否會出現(xiàn)最合適AI+人合作的語言?如果有,大概率會在c語言基礎(chǔ)上擴(kuò)展概念和范式。畢竟c的數(shù)據(jù)基礎(chǔ)更好。個人傾向于認(rèn)為rust有點過設(shè)計了。cpp過于復(fù)雜,也過設(shè)計了。個人感覺未來AI更適合使用以c為基礎(chǔ)的語言,適當(dāng)擴(kuò)展一些概念。
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://kaisery.github.io/trpl-zh-cn/title-page.html | |
標(biāo)準(zhǔn)庫 | stdio.h … https://www.runoob.com/cprogramming/c-standard-library.html | https://doc.rust-lang.org/stable/std/all.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編譯器 | ||
語言類型 | 面向過程 | 多范式:面向?qū)ο?、函?shù)式和并發(fā)編程 |
注釋 | // or /* */ | // or /* */ |
行結(jié)尾 | ; | ; |
路徑分隔符 | / or \ | :: |
代碼塊 | {} | {} |
函數(shù)體表達(dá)式 | 無 | {} |
大小寫 | 區(qū)分 | 同c |
標(biāo)識符 | 以字母 A-Z 或 a-z 或下劃線 _ 開始,后跟零個或多個字母、下劃線和數(shù)字(0-9)。 | 同c |
關(guān)鍵字 | https://www.runoob.com/cprogramming/c-basic-syntax.html | https://github.com/rust-lang/book/blob/main/src/appendix-01-keywords.md |
keys | auto,break,case,char,const,continue,default,do,double, | as,async,await,break,const,continue,crate,dyn,else,enum,extern, |
else,enum,extern,float,for,goto,if,int,long,register,return,short, | false,fn,for,if,impl,in,let,loop,match,mod,move,mut,pub,ref,return, | |
signed,sizeof,static,struct,switch,typedef,unsigned,union,void,volatile,while | Self,self,static,struct,super,trait,true,type,union,unsafe,use,where,while, | |
c99 keys | _Bool,_Complex,_Imaginary,inline,restrict | abstract,become,box,do,final,macro,override,priv,try,typeof,unsized,virtual,yield, |
c11 keys | _Alignas,_Alignof,_Atomic,_Generic,_Noreturn,_Static_assert,_Thread_local | |
數(shù)據(jù)類型 | 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 | |
void | 無??赵M () “unit type” | |
unicode | 無 | char(4byte)建議utf8 |
字符串 | char str[] = “RUNOOB”; | let str = String::from(“RUNOOB”); let string = String::new(); let one = 1.to_string(); |
字符串切片 | 自行實現(xiàn) | let part1 = &str[0…5];//類似string_view |
非字符串切片 | 自行實現(xiàn) | let part = &arr[0…3]; |
變量 | int i=0; | let i:i32 = 0; |
變量聲明 | extern int i; | extern { static i: i32;} |
重影(Shadowing) | 無 | let x = 5; let x = x + 1; |
左值 | 指向內(nèi)存位置的表達(dá)式 | 同c |
右值 | 存儲在內(nèi)存中某些地址的數(shù)值 | 同c |
常量 | long myLong = 100000L;float myFloat = 3.14f;char myChar = ‘a(chǎn)’;char myString[] = “Hello, world!”; | const MY_LONG: i64 = 100000; const MY_STRING: &str = “Hello, world!”; … |
#define PI 3.14159 | const PI: f64 = 3.14159; | |
const int MAX_VALUE = 100; | const MAX_VALUE:u32 = 100; | |
存儲類型 | auto,register,static,extern | static,extern |
所有權(quán) | 無 | 每個值都有一個變量,稱為其所有者。一次只能有一個所有者。當(dāng)所有者不在程序運行范圍時,該值將被刪除。 |
生命周期 | {}代碼塊內(nèi) | 同c |
靜態(tài)生命周期 | static | &'static |
生命周期注釋 | 無 | 描述引用生命周期。聲明兩個引用的生命周期一致。fn longer<'a>(s1: &'a str, s2: &'a str) -> &'a str{…} |
移動(Move) | 無 | let s1 = String::from(“hello”);let s2 = s1; println!(“{}, world!”, s1); // 錯誤!s1 已經(jīng)失效 |
克隆(Clone) | 無 | let s1 = String::from(“hello”);let s2 = s1.clone(); println!(“{}, world!”, s1); |
算術(shù)運算符 | + -*/% ++ – | + -*/% |
關(guān)系運算符 | == != > < >= <= | 同c |
邏輯運算符 | && || ! | 同c |
位運算符 | & | ^ ~ << >> | 同c |
賦值運算符 | = += -= *= /= %= &= |= ^= <<= >>= | 同c |
三元運算符 | (a > 0)? 1:-1 | if (a > 0) { 1 } else { -1 } |
sizeof運算符 | sizeof() | use std::mem; std::mem::size_of(…) |
引用和解引用運算符 | & * | & * |
區(qū)間運算符 | 無 | … …= |
運算符優(yōu)先級 | https://www.runoob.com/cprogramming/c-operators.html | |
用()改變求值順序 | 同c | |
判斷/條件語句 | if(…){…}else{…} | if(…){…}else{…} 可以不要(),僅支持bool判斷 |
switch分支判斷 | switch(…){case …:break;case …:break;default:…;} | 無,用match替代 |
if let | 無,用if替代 | if let 0 = i {println!(“zero”);}else{…} |
循環(huán) | for(;; ){} while(){} do{}while(); | while(){} for i in a.iter(){…} loop{… break; …} |
break,continue | break,continue | |
goto | 無 | |
函數(shù)定義 | int max(int x, int y) {…} | fn max(x: i32, y: i32)->i32 {…} |
函數(shù)嵌套 | 無 | fn main() { fn five() -> i32 {5}} |
函數(shù)調(diào)用 | int ret = max(a, b); | let ret: i32 = max(a, b); |
參數(shù)作用域 | 全局變量,局部變量,形式參數(shù)為局部變量 | 同c。多了借用(borrowing)和可變借用(mutable borrowing)概念 |
可變參數(shù) | … 具體示例見printf實現(xiàn) | 無 |
數(shù)組 | int i_array[] = {1, 2, 3, 4, 5}; | let mut i_array: [i32; 5] = [1, 2, 3, 4, 5]; |
向量 | 無。用數(shù)組替代 | let vector: Vec = Vec::new(); let vector = vec![1, 2, 4, 8];外加大量的方法。 |
數(shù)組下標(biāo) | >=0 | 同c |
數(shù)組訪問 | i_array[i] | i_array[i] |
多維數(shù)組 | int i_a2[3][3]; | let mut i_a2: [[i32; 3]; 3] = [[0; 3]; 3]; |
動態(tài)數(shù)組 | 通過指針和malloc實現(xiàn) | let mut dynamic_array: Vec< i32 > = Vec::new(); |
map | 無。自行實現(xiàn)。 | use std::collections::HashMap; |
指針 | 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 | 同c |
函數(shù)指針 | typedef int (*fun_ptr)(int,int); | let func_ptr: fn(i32,i32) -> i32; |
枚舉 | 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”); }} | ||
結(jié)構(gòu)體 | struct SIMPLE{ int a; char b; double c;}; | struct SIMPLE{ a:i32; b:i8; c:f64;} |
復(fù)合類型/元組 | 無 | let tup: (i32, f64, u8) = (500, 6.4, 1);let (x, y, z) = tup; |
元組結(jié)構(gòu)體 | 無 | struct Color(u8, u8, u8);let black = Color(0, 0, 0); |
單元結(jié)構(gòu)體 | 無 | struct UnitStruct;//無成員 |
結(jié)構(gòu)體成員訪問 | . 或 -> | 只用. 沒有-> |
結(jié)構(gòu)體方法 | 無 | struct Rectangle { width: u32, height: u32,} impl Rectangle { fn area(&self) -> u32 {self.width * self.height}} |
結(jié)構(gòu)體關(guān)聯(lián)函數(shù) | 無 | impl Rectangle { fn create(width: u32, height: u32) -> Rectangle { Rectangle { width, height } }} //impl 可以寫多次 |
輸出結(jié)構(gòu)體 | 無 | println!(“rect1 is {:?}”, rect1);//屬性較多的話可以使用另一個占位符 {:#?} |
共用體 | union Data{ int i; float f; char str[20];}; | enum Data { Integer(i32), Float(f32), String([char; 20]),} |
共用體成員訪問 | 同結(jié)構(gòu)體 | match … |
位域 | struct bs{ int a:8; int b:2; int c:6;}; | #[repr?] #[derive(Debug)] struct BitStruct { a: u8, b: u8, c: u8,} |
位域成員訪問 | 同結(jié)構(gòu)體 | 同c |
別名 | typedef unsigned char BYTE; | type BYTE = u8; |
程序入口 | int main( int argc, char *argv[] ) | fn main(){let args = std::env::args();println!(“{:?}”, args);} |
輸入 | int scanf(const char *format, …) 函數(shù)從標(biāo)準(zhǔn)輸入流 stdin 讀取輸入 | stdin().read_line(&mut str_buf).expect(“Failed to read line.”); |
輸出 | int printf(const char *format, …) 函數(shù)把輸出寫入到標(biāo)準(zhǔn)輸出流 stdout | println!(“Your input line is \n{}”, str_buf); |
文件讀寫 | 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(…)… | use std::fs; let text = fs::read_to_string(“D:\text.txt”).unwrap(); let mut file = fs::File::open(“D:\text.txt”).unwrap(); file.read(&mut buffer).unwrap();fs::write(…) … |
文件打開權(quán)限設(shè)置 | const char *mode | let mut file = OpenOptions::new().read(true).write(true).open(“D:\text.txt”)?; |
預(yù)處理 | #define #include #undef #ifdef #ifndef #if #else #elif #endif | 無,用宏替代 |
#error | compile_error! | |
#pragma | #[allow()] 和 #[warn()] 等 | |
預(yù)定義宏 | __DATE__ __TIME__ __FILE__ __LINE__ __STDC__ | 無。運行時有部分對應(yīng)。 |
預(yù)處理器運算符 | \ # ## | 無 |
宏帶參數(shù) | #define square(x) ((x) * (x)) | macro_rules! square { (KaTeX parse error: Expected '}', got 'EOF' at end of input: x:expr) => { (x) * ($x) };} |
頭文件 | #include <stdio.h> #include “my_head.h” | use std::io::stdin; |
類型轉(zhuǎn)換 | int i=3;double d = (double)i; | let d: f64 = i as f64; |
錯誤處理 | extern int errno ;fprintf(stderr, “錯誤號: %d\n”, errno); perror(“通過 perror 輸出錯誤”); fprintf(stderr, “錯誤號對應(yīng)的描述: %s\n”, strerror( errno )); | 可恢復(fù)錯誤用 Result<T, E> 類來處理,對于不可恢復(fù)錯誤使用 panic! 宏來處理。支持回溯。 |
回溯 | 非自帶 | 支持。run with RUST_BACKTRACE=1 environment variable to display a backtrace. |
Result<T, E> | 用int自行實現(xiàn) | enum Result<T, E> { Ok(T), Err(E),} 在 Rust 標(biāo)準(zhǔn)庫中可能產(chǎn)生異常的函數(shù)的返回值都是 Result 類型的。 |
?符號 | 無 | ? 符僅用于返回值類型為 Result<T, E> 的函數(shù) |
unwrap,expect | 無 | 可恢復(fù)錯誤按不可恢復(fù)錯誤處理 |
除0 | 異常,崩潰 | 線程 panic,異常,崩潰 |
程序退出狀態(tài) | exit(EXIT_SUCCESS); 0為正常狀態(tài)。EXIT_FAILURE==-1 | process::exit(0); |
遞歸 | 一般通過遞歸函數(shù)實現(xiàn) | 同c |
內(nèi)存管理 | malloc free | 通過所有權(quán)和智能指針(如 Box< T>、Rc< T> 和 Arc< T>) |
命令行參數(shù) | int main( int argc, char *argv[] ) | fn main()無,通過let args: Vec< String> = env::args().collect();獲得 |
隨機(jī)數(shù) | srand(time(0)) rand() | use rand::Rng; rand::rngs::StdRng::seed_from_u64(seed);rng.gen(); |
排序 | void qsort(void *b, size_t n, size_t s, compar_fn cmp); | sort() |
查找 | void *bsearch (const void *__key, const void *__base, size_t __nmemb, size_t __size, __compar_fn_t __compar); | binary_search(t) |
組織管理 | .h.c.lib.dll … | 箱(Crate)、包(Package)、模塊(Module) |
訪問權(quán) | 無 | 公共(public)和私有(private),默認(rèn)私有,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 關(guān)鍵字開始描述。相對路徑從 self 或 super 關(guān)鍵字或一個標(biāo)識符開始描述。 |
use | 無 | use crate::nation::government::govern as nation_govern; |
泛型函數(shù) | _Generic | fn max< T >(array: &[T]) -> T {…} |
泛型結(jié)構(gòu) | 無 | struct Point< T > {x: T, y: T} |
特性(trait) | 無 | trait Descriptive { fn describe(&self) -> String;} impl < 特性名 > for < 所實現(xiàn)的類型名 > |
接口(Interface) | 無。通過一組函數(shù)指針實現(xiàn)。 | trait類似,但可以定義默認(rèn)實現(xiàn) |
繼承 | 無。通過派生類包含基類成員實現(xiàn) | 同c |
多態(tài) | 無。通過函數(shù)指針實現(xiàn)。 | 通過特性(trait)實現(xiàn) |
并發(fā)(concurrent) | 自行解決 | 安全高效的處理并發(fā)是 Rust 誕生的目的之一。編譯期解決部分問題。 |
并行(parallel) | thread | openmp |
線程(thread) | 系統(tǒng)庫 | use std::thread;thread::spawn(…); |
閉包 | 無,函數(shù)指針 | |arg1, arg2, …| -> T {…} |
Lambda | 無,函數(shù)指針 | 無,閉包 |
實現(xiàn)消息 | 無 | 通道(channel)=發(fā)送者(transmitter)+接收者(receiver)。use std::sync::mpsc;let (tx, rx) = mpsc::channel(); |
代碼例子 | https://www.runoob.com/cprogramming/c-examples.html | |