日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
半小時(shí)入門Rust,這是一篇Rust代碼風(fēng)暴

據(jù)說很多開發(fā)者一天入門 Python,兩天上手 Go,但到了 Rust 就會(huì)發(fā)現(xiàn)畫風(fēng)隱約有些不對(duì)。它從語法到特性,似乎都要復(fù)雜一些。本文介紹的就是 Rust,作者表示,通過解析大量代碼,「半個(gè)小時(shí)」就能入門 Rust。

成都創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供喀喇沁網(wǎng)站建設(shè)、喀喇沁做網(wǎng)站、喀喇沁網(wǎng)站設(shè)計(jì)、喀喇沁網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、喀喇沁企業(yè)網(wǎng)站模板建站服務(wù),十載喀喇沁做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。

Rust 是一門系統(tǒng)編程語言,專注于安全,尤其是并發(fā)安全。它支持函數(shù)式和命令式以及泛型等編程范式的多范式語言,且 TensorFlow 等深度學(xué)習(xí)框架也把它作為一個(gè)優(yōu)秀的前端語言。

Rust 在語法上和 C、C++類似,都由花括弧限定代碼塊,并有相同的控制流關(guān)鍵字,但 Rust 設(shè)計(jì)者想要在保證性能的同時(shí)提供更好的內(nèi)存安全。Rust 自 2016 年就已經(jīng)開源了,在各種開發(fā)者調(diào)查中,它也總能獲得「最受歡迎的語言」這一稱贊,目前該開源項(xiàng)目已有 42.9K 的 Star 量。

機(jī)器之心的讀者大多數(shù)都非常熟悉 Python,而 Rust 就沒那么熟悉了。在 Amos 最近的一篇博文中,他表示如果閱讀他的作品,我們半個(gè)小時(shí)就能入門 Rust。因此在這篇文章中,我們將介紹該博文的主要內(nèi)容,它并不關(guān)注于 1 個(gè)或幾個(gè)關(guān)鍵概念,相反它希望通過代碼塊縱覽 Rust 的各種特性,包括各種關(guān)鍵詞與符號(hào)的意義。

在 HackNews 上,很多開發(fā)者表示這一份入門教程非常實(shí)用,Rust 的入門門檻本來就比較高,如果再介紹各種復(fù)雜的概念與特性,很容易出現(xiàn)「從入門到勸退」。因此這種從實(shí)例代碼出發(fā)的教程,非常有意義。

從變量說起

let 能綁定變量:

 
 
 
 
  1. let x; // declare "x"
  2. x = 42; // assign 42 to "x"
  3. let x = 42; // combined in one line

可以使用 :來制定變量的數(shù)據(jù)類型,以及數(shù)據(jù)類型注釋:

 
 
 
 
  1. let x: i32; // `i32` is a signed 32-bit integer
  2. x = 42;
  3. // there's i8, i16, i32, i64, i128
  4. // also u8, u16, u32, u64, u128 for unsigned
  5. let x: i32 = 42; // combined in one line

如果你聲明一個(gè)變量并在初始化之前就調(diào)用它,編譯器會(huì)報(bào)錯(cuò):

 
 
 
 
  1. let x;
  2. foobar(x); // error: borrow of possibly-uninitialized variable: `x`
  3. x = 42;

然而,這樣做完全沒問題:

 
 
 
 
  1. let x;
  2. x = 42;
  3. foobar(x); // the type of `x` will be inferred from here

下劃線表示特殊的命名,或者更確切地說是「缺失的命名」,它和 Python 的用法有點(diǎn)像:

 
 
 
 
  1. // this does *nothing* because 42 is a constant
  2. let _ = 42;
  3. // this calls `get_thing` but throws away its result
  4. let _ = get_thing();

以下劃線開頭的命名是常規(guī)命名,只是編譯器不會(huì)警告它們未被使用:

 
 
 
 
  1. // we may use `_x` eventually, but our code is a work-in-progress
  2. // and we just wanted to get rid of a compiler warning for now.
  3. let _x = 42;

相同命名的單獨(dú)綁定是可行的,第一次綁定的變量會(huì)取消:

 
 
 
 
  1. let x = 13;
  2. let x = x + 3;
  3. // using `x` after that line only refers to the second `x`,
  4. // the first `x` no longer exists.

Rust 有元組類型,可以將其看作是「不同數(shù)據(jù)類型值的定長集合」。

 
 
 
 
  1. let pair = ('a', 17);
  2. pair.0; // this is 'a'
  3. pair.1; // this is 17

如果真的想配置 pair 的數(shù)據(jù)類型,可以這么寫:

 
 
 
 
  1. let pair: (char, i32) = ('a', 17);

元組在賦值時(shí)可以被拆解,這意味著它們被分解成各個(gè)字段:

 
 
 
 
  1. let (some_char, some_int) = ('a', 17);
  2. // now, `some_char` is 'a', and `some_int` is 17

當(dāng)一個(gè)函數(shù)返還一個(gè)元組時(shí)會(huì)非常有用:

 
 
 
 
  1. let (left, right) = slice.split_at(middle);

當(dāng)然,在解構(gòu)一個(gè)元組時(shí),可以只分離它的一部分:

 
 
 
 
  1. let (_, right) = slice.split_at(middle);

分號(hào)表示語句的結(jié)尾:

 
 
 
 
  1. let x = 3;
  2. let y = 5;
  3. let z = y + x;

不加分號(hào)意味著語句可以跨多行:

 
 
 
 
  1. let x = vec![1, 2, 3, 4, 5, 6, 7, 8]
  2. .iter()
  3. .map(|x| x + 3)
  4. .fold(0, |x, y| x + y);

函數(shù)來了

fn 聲明一個(gè)函數(shù)。下面是一個(gè)空函數(shù):

 
 
 
 
  1. fn greet() {
  2. println!("Hi there!");
  3. }

這是一個(gè)返還 32 位帶符號(hào)整數(shù)值的函數(shù)。箭頭表示返還類型:

 
 
 
 
  1. fn fair_dice_roll() -> i32 {
  2. 4
  3. }

花括號(hào)表示了一個(gè)代碼塊,且擁有其自己的作用域:

 
 
 
 
  1. // This prints "in", then "out"
  2. fn main() {
  3. let x = "out";
  4. {
  5. // this is a different `x`
  6. let x = "in";
  7. println!(x);
  8. }
  9. println!(x);
  10. }

代碼塊也是表示式,表示其計(jì)算為一個(gè)值。

 
 
 
 
  1. // this:
  2. let x = 42;
  3. // is equivalent to this:
  4. let x = { 42 };

在一個(gè)代碼塊中,可以有多個(gè)語句:

 
 
 
 
  1. let x = {
  2. let y = 1; // first statement
  3. let z = 2; // second statement
  4. y + z // this is the *tail* - what the whole block will evaluate to
  5. };

這也是為什么「省略函數(shù)末尾的分號(hào)」等同于加上了 Retrun,這些都是等價(jià)的:

 
 
 
 
  1. fn fair_dice_roll() -> i32 {
  2. return 4;
  3. }
  4. fn fair_dice_roll() -> i32 {
  5. 4
  6. }

if 條件語句也是表達(dá)式:

 
 
 
 
  1. fn fair_dice_roll() -> i32 {
  2. if feeling_lucky {
  3. 6
  4. } else {
  5. 4
  6. }
  7. }

match 匹配器也是一個(gè)表達(dá)式:

 
 
 
 
  1. fn fair_dice_roll() -> i32 {
  2. match feeling_lucky {
  3. true => 6,
  4. false => 4,
  5. }
  6. }

Dots 通常用于訪問某個(gè)對(duì)象的字段:

 
 
 
 
  1. let a = (10, 20);
  2. a.0; // this is 10
  3. let amos = get_some_struct();
  4. amos.nickname; // this is "fasterthanlime"

或者調(diào)用對(duì)象的方法:

 
 
 
 
  1. let nick = "fasterthanlime";
  2. nick.len(); // this is 14

雙冒號(hào)與此類似,但可對(duì)命名空間進(jìn)行操作。在此舉例中,std 是一個(gè) crate (~ a library),cmp 是一個(gè) module(~ a source file),以及 min 是個(gè)函數(shù):

 
 
 
 
  1. let least = std::cmp::min(3, 8); // this is 3

use 指令可用于從其他命名空間中「引入范圍」命名:

 
 
 
 
  1. use std::cmp::min;
  2. let least = min(7, 1); // this is 1

在 use 指令中,花括號(hào)還有另一個(gè)含義:「globs」,因此可以同時(shí)導(dǎo)入 min 以及 max:

 
 
 
 
  1. // this works:
  2. use std::cmp::min;
  3. use std::cmp::max;
  4. // this also works:
  5. use std::cmp::{min, max};
  6. // this also works!
  7. use std::{cmp::min, cmp::max};

通配符(*)允許從命名空間導(dǎo)入符號(hào):

 
 
 
 
  1. // this brings `min` and `max` in scope, and many other things
  2. use std::cmp::*;

Types 也是命名空間和方法,它可以作為常規(guī)函數(shù)調(diào)用:

 
 
 
 
  1. let x = "amos".len(); // this is 4
  2. let x = str::len("amos"); // this is also 4

str 是一個(gè)基元數(shù)據(jù)類型,但在默認(rèn)情況下,許多非基元數(shù)據(jù)類型也在作用域中。

 
 
 
 
  1. // `Vec` is a regular struct, not a primitive type
  2. let v = Vec::new();
  3. // this is exactly the same code, but with the *full* path to `Vec`
  4. let v = std::vec::Vec::new()

至于為什么可行,因?yàn)?Rust 在每個(gè)模塊的開頭都插入了:

 
 
 
 
  1. use std::prelude::v1::*;

再說說結(jié)構(gòu)體

使用 struct 關(guān)鍵字聲明結(jié)構(gòu)體:

 
 
 
 
  1. struct Vec2 {
  2. x: f64, // 64-bit floating point, aka "double precision"
  3. y: f64,
  4. }

可以使用結(jié)構(gòu)語句初始化:

 
 
 
 
  1. let v1 = Vec2 { x: 1.0, y: 3.0 };
  2. let v2 = Vec2 { y: 2.0, x: 4.0 };
  3. // the order does not matter, only the names do

有一個(gè)快捷方式可以從另一個(gè)結(jié)構(gòu)體初始化本結(jié)構(gòu)體的其余字段:

 
 
 
 
  1. let v3 = Vec2 {
  2. x: 14.0,
  3. ..v2
  4. };

這就是所謂的「結(jié)構(gòu)體更新語法」只能發(fā)生在最后一個(gè)位置,不能在其后面再跟一個(gè)逗號(hào)。

注意其余字段可以表示所有字段:

 
 
 
 
  1. let v4 = Vec2 { ..v3 };

結(jié)構(gòu)體與元組一樣,可以被解構(gòu)。例如一個(gè)有效的 let 模式:

 
 
 
 
  1. let (left, right) = slice.split_at(middle);
  2. let v = Vec2 { x: 3.0, y: 6.0 };
  3. let Vec2 { x, y } = v;
  4. // `x` is now 3.0, `y` is now `6.0`
  5. let Vec2 { x, .. } = v;
  6. // this throws away `v.y`

讓 let 模式在 if 里可以作為條件:

 
 
 
 
  1. struct Number {
  2. odd: bool,
  3. value: i32,
  4. }
  5. fn main() {
  6. let one = Number { odd: true, value: 1 };
  7. let two = Number { odd: false, value: 2 };
  8. print_number(one);
  9. print_number(two);
  10. }
  11. fn print_number(n: Number) {
  12. if let Number { odd: true, value } = n {
  13. println!("Odd number: {}", value);
  14. } else if let Number { odd: false, value } = n {
  15. println!("Even number: {}", value);
  16. }
  17. }
  18. // this prints:
  19. // Odd number: 1
  20. // Even number: 2

多分支的 match 也是條件模式,就像 if let:

 
 
 
 
  1. fn print_number(n: Number) {
  2. match n {
  3. Number { odd: true, value } => println!("Odd number: {}", value),
  4. Number { odd: false, value } => println!("Even number: {}", value),
  5. }
  6. }
  7. // this prints the same as before

match 必須是囊括所有情況的的:至少需要匹配一個(gè)條件分支。

 
 
 
 
  1. fn print_number(n: Number) {
  2. match n {
  3. Number { value: 1, .. } => println!("One"),
  4. Number { value: 2, .. } => println!("Two"),
  5. Number { value, .. } => println!("{}", value),
  6. // if that last arm didn't exist, we would get a compile-time error
  7. }
  8. }

如果非常難實(shí)現(xiàn),_ 那么可以作用一個(gè)“包羅萬象”的模式:

 
 
 
 
  1. fn print_number(n: Number) {
  2. match n.value {
  3. 1 => println!("One"),
  4. 2 => println!("Two"),
  5. _ => println!("{}", n.value),
  6. }
  7. }

Type 別名

我們可以使用 type 關(guān)鍵字聲明另一類型的別名,然后就可以像使用一個(gè)真正的類型一樣使用這種類型。例如定義 Name 這種數(shù)據(jù)類型為字符串,后面就可以直接使用 Name 這種類型了。

你可以在方法中聲明不同的數(shù)據(jù)類型:

 
 
 
 
  1. struct Number {
  2. odd: bool,
  3. value: i32,
  4. }
  5. impl Number {
  6. fn is_strictly_positive(self) -> bool {
  7. self.value > 0
  8. }
  9. }

然后就如同往常那樣使用:

 
 
 
 
  1. fn main() {
  2. let minus_two = Number {
  3. odd: false,
  4. value: -2,
  5. };
  6. println!("positive? {}", minus_two.is_strictly_positive());
  7. // this prints "positive? false"
  8. }

默認(rèn)情況下,聲明變量后它就就是不可變的,如下 odd 不能被重新賦值:

 
 
 
 
  1. fn main() {
  2. let n = Number {
  3. odd: true,
  4. value: 17,
  5. };
  6. n.odd = false; // error: cannot assign to `n.odd`,
  7. // as `n` is not declared to be mutable
  8. }

不可變的變量聲明,其內(nèi)部也是不可變的,它也不能重新分配值:

 
 
 
 
  1. fn main() {
  2. let n = Number {
  3. odd: true,
  4. value: 17,
  5. };
  6. n = Number {
  7. odd: false,
  8. value: 22,
  9. }; // error: cannot assign twice to immutable variable `n`
  10. }

mut 可以使變量聲明變?yōu)榭勺兊模?/p>

 
 
 
 
  1. fn main() {
  2. let mut n = Number {
  3. odd: true,
  4. value: 17,
  5. }
  6. n.value = 19; // all good
  7. }

Traits 描述的是多種數(shù)據(jù)類型的共同點(diǎn):

 
 
 
 
  1. trait Signed {
  2. fn is_strictly_negative(self) -> bool;
  3. }

我們可以在我們定義的 Type 類型中定義 Traits:

 
 
 
 
  1. impl Signed for Number {
  2. fn is_strictly_negative(self) -> bool {
  3. self.value < 0
  4. }
  5. }
  6. fn main() {
  7. let n = Number { odd: false, value: -44 };
  8. println!("{}", n.is_strictly_negative()); // prints "true"
  9. }

外部類型(foreign type)中定義的 Trait:

 
 
 
 
  1. impl Signed for i32 {
  2. fn is_strictly_negative(self) -> bool {
  3. self < 0
  4. }
  5. }
  6. fn main() {
  7. let n: i32 = -44;
  8. println!("{}", n.is_strictly_negative()); // prints "true"
  9. }

impl 模塊通常會(huì)帶有一個(gè) Type 類型,所以在模塊內(nèi),Self 就表示該類型:

 
 
 
 
  1. impl std::ops::Neg for Number {
  2. type Output = Self;
  3. fn neg(self) -> Self {
  4. Self {
  5. value: -self.value,
  6. odd: self.odd,
  7. }
  8. }
  9. }

有一些traits只是作為標(biāo)記,它們并不是說 Type 類型實(shí)現(xiàn)了某些方法,它只是表明某些東西能通過Type類型完成。例如,i32 實(shí)現(xiàn)了Copy,那么以下代碼就是可行的:

 
 
 
 
  1. fn main() {
  2. let a: i32 = 15;
  3. let b = a; // `a` is copied
  4. let c = a; // `a` is copied again
  5. }

下面的代碼也是能運(yùn)行的:

 
 
 
 
  1. fn print_i32(x: i32) {
  2. println!("x = {}", x);
  3. }
  4. fn main() {
  5. let a: i32 = 15;
  6. print_i32(a); // `a` is copied
  7. print_i32(a); // `a` is copied again
  8. }

但是 Number 的結(jié)構(gòu)體并不能用于 Copy,所以下面的代碼會(huì)報(bào)錯(cuò):

 
 
 
 
  1. fn main() {
  2. let n = Number { odd: true, value: 51 };
  3. let m = n; // `n` is moved into `m`
  4. let o = n; // error: use of moved value: `n`
  5. }

同樣下面的代碼也不會(huì) Work:

 
 
 
 
  1. fn print_number(n: Number) {
  2. println!("{} number {}", if n.odd { "odd" } else { "even" }, n.value);
  3. }
  4. fn main() {
  5. let n = Number { odd: true, value: 51 };
  6. print_number(n); // `n` is moved
  7. print_number(n); // error: use of moved value: `n`
  8. }

但是如果print_number有一個(gè)不可變r(jià)eference,那么 Copy 就是可行的:

 
 
 
 
  1. fn print_number(n: &Number) {
  2. println!("{} number {}", if n.odd { "odd" } else { "even" }, n.value);
  3. }
  4. fn main() {
  5. let n = Number { odd: true, value: 51 };
  6. print_number(&n); // `n` is borrowed for the time of the call
  7. print_number(&n); // `n` is borrowed again
  8. }

如果函數(shù)采用了可變r(jià)eference,那也是可行的,只不過需要在變量聲明中帶上 mut。

 
 
 
 
  1. fn invert(n: &mut Number) {
  2. n.value = -n.value;
  3. }
  4. fn print_number(n: &Number) {
  5. println!("{} number {}", if n.odd { "odd" } else { "even" }, n.value);
  6. }
  7. fn main() {
  8. // this time, `n` is mutable
  9. let mut n = Number { odd: true, value: 51 };
  10. print_number(&n);
  11. invert(&mut n); // `n is borrowed mutably - everything is explicit
  12. print_number(&n);
  13. }

Copy 這類標(biāo)記型的traits并不帶有方法:

 
 
 
 
  1. // note: `Copy` requires that `Clone` is implemented too
  2. impl std::clone::Clone for Number {
  3. fn clone(&self) -> Self {
  4. Self { ..*self }
  5. }
  6. }
  7. impl std::marker::Copy for Number {}

現(xiàn)在 Clone 仍然可以用于:

 
 
 
 
  1. fn main() {
  2. let n = Number { odd: true, value: 51 };
  3. let m = n.clone();
  4. let o = n.clone();
  5. }

但是Number的值將不會(huì)再移除:

 
 
 
 
  1. fn main() {
  2. let n = Number { odd: true, value: 51 };
  3. let m = n; // `m` is a copy of `n`
  4. let o = n; // same. `n` is neither moved nor borrowed.
  5. }

有一些traits很常見,它們可以通過使用derive 屬性自動(dòng)實(shí)現(xiàn):

 
 
 
 
  1. #[derive(Clone, Copy)]
  2. struct Number {
  3. odd: bool,
  4. value: i32,
  5. }
  6. // this expands to `impl Clone for Number` and `impl Copy for Number` blocks.

看上去,整篇教程都在使用大量代碼解釋 Rust 的各種語句與用法??赡芪覀儠?huì)感覺博客結(jié)構(gòu)不是太明確,但是實(shí)例驅(qū)動(dòng)的代碼學(xué)習(xí)確實(shí)更加高效。尤其是對(duì)于那些有一些編程基礎(chǔ)的同學(xué),他們可以快速抓住 Rust 語言的特點(diǎn)與邏輯。

最后,這篇文章并沒有展示博客所有的內(nèi)容,如果讀者想真正入門 Rust 語言,推薦可以查閱原博客。


文章標(biāo)題:半小時(shí)入門Rust,這是一篇Rust代碼風(fēng)暴
網(wǎng)頁路徑:http://www.5511xx.com/article/dpegijs.html