rust面向对象_面向初学者的Rust操作员综合教程
rust面向?qū)ο?/p>
目錄 (Table of Contents)
🦀 Introduction🦀 Arithmetic Operators🦀 Comparison Operators🦀 Logical Operators🦀 Bitwise Operators🦀 Compound Assignment Operators🦀 Operator Overloading🦀 XOR and Bitwise Operators Truth Table🦀 Problem 1: Single Number🦀 Method and Associated Functions🦀 Solution Using an Associated Function🦀 Problem 2: Number of Steps to Reduce a Number to Zero🦀 Conclusion
🦀 介紹 🦀 算術(shù)運算符 🦀 比較運算符 🦀 邏輯運算符 🦀 位運算符 🦀 復(fù)合賦值運算符 🦀 運算符重載 🦀 XOR和位運算符真值表 🦀 問題1:單一號碼 🦀 的方法和相關(guān)聯(lián)的功能 🦀 解決方案使用相關(guān)聯(lián)的功能 🦀 問題2:數(shù)數(shù)減少到零的步驟結(jié)論
介紹 (Introduction)
Operators tell the compiler or interpreter to perform a specific mathematical, relational, or logical operation. Many programming languages make use of similar operator symbols.
運算符告訴編譯器或解釋器執(zhí)行特定的數(shù)學(xué),關(guān)系或邏輯運算。 許多編程語言都使用類似的運算符。
We will go through the important arithmetic, relational, and logical operators available in Rust and we will compare them to Python.
我們將介紹Rust中可用的重要算術(shù),關(guān)系和邏輯運算符,并將它們與Python進行比較。
We will learn the differences between methods and associated functions.
我們將學(xué)習(xí)方法與關(guān)聯(lián)函數(shù)之間的差異。
We also convert two simple Python codes to Rust codes to learn more about Rust programming.
我們還將兩個簡單的Python代碼轉(zhuǎn)換為Rust代碼,以了解有關(guān)Rust編程的更多信息。
Let’s get started!
讓我們開始吧!
算術(shù)運算符 (Arithmetic Operators)
Rust and Python Arithmetic Operators. Image by the author.Rust和Python算術(shù)運算符。 圖片由作者提供。Python and Rust share the same arithmetic symbols as you see in the above table. Rust calls % as Remainder instead of the Modulus.
Python和Rust共享與上表相同的算術(shù)符號。 Rust將%稱為余數(shù)而不是模量 。
We will cover “Rust Overloading Trait” later in the Operator Overloading.
我們將在稍后的“ 操作員重載 ”中介紹“Rust重載特征”。
Rust Arithmetic Operators examples.Rust算術(shù)運算符示例。Output:
輸出:
a: 20, b: 20+1=21, c: 20-2=18, d: 20*3=60, e: 20/4=5, f: 20%3=2In Rust, you can’t use different data types in an operation. For example, if you try to subtract an unsigned integer from a signed integer, it will fail:
在Rust中,您不能在操作中使用不同的數(shù)據(jù) 類型 。 例如,如果嘗試從有符號整數(shù)中減去無符號 整數(shù) ,它將失敗:
// This will fail.fn main() {
let a = 8u8;
let b = 2i32;
println!("{}", a - b);
}
Rust uses the as keyword to cast between primitive types. Please read more about the cast in Rust here.
Rust使用as 關(guān)鍵字在原始類型之間進行轉(zhuǎn)換。 請在此處詳細了解Rust中的演員表。
Using the as keyword for casting.使用as關(guān)鍵字進行轉(zhuǎn)換。Output:
輸出:
6指數(shù) (Exponent)
Python uses the ** symbol for exponents:
Python使用**符號表示指數(shù):
Python Exponent examples.Python指數(shù)示例。Output:
輸出:
2^3 is 83^3 is 27
3^3.2 is 33.63473536961897
Rust uses pow, powi, and powf depends on the type:
Rust使用pow , powi和powf 取決于類型:
Rust Exponent examples.銹指數(shù)示例。Output:
輸出:
2 ^ 3 in Rust: 2u8.pow(3) = 82 ^ 3 in Rust: 2i32.pow(3) is 8
3.0 ^ 3 in Rust: 3.0f32.powi(3) 27
3.0 ^ 3.2 in Rust: 3.0_f32.powf(3.2) is 33.63474
a = 3, a ^ 3 in Rust: i32::pow(a,3) = 27
b = 3.1, b ^ 3 in Rust: f64::powi(b, 3) = 29.791000000000004
b = 3.1, b ^ PI in Rust: std::f64::consts::PI) = 34.96699308140392
In Rust, you can annotate a number type like 2u8 or 2_u8. u8 is an unsigned 8-bit integer type and i32 is a signed integer type.
在Rust中,您可以注釋數(shù)字類型,例如2u8或2_u8 。 u8是無符號的8位整數(shù)類型,而i32是有符號的整數(shù)類型 。
i32 and f32 have a group of built-in methods. All the integer types u8, u16, u32, u64, u128, i16,i32, i64 , i128, isize, and usize have the pow method.
i32和f32具有一組內(nèi)置方法。 所有整數(shù)類型u8 , u16 , u32 , u64 , u128 , i16 , i32 , i64 , i128 , isize和usize有pow的方法。
pub fn pow(self, exp: u32) -> i32The above definition tells you that using the pow method raises self to the power of exp (which is u32) and returns i32 (a signed integer).
上述定義告訴你,使用pow方法提高自我的力量exp (這是u32 ),并返回i32 (有符號整數(shù))。
The floating-point types, f32 and f64 have powi and powf methods.
浮點類型 f32和f64具有powi和powf方法。
powi raises a number to an integer power and powf raises a number to a floating-point power.
powi將數(shù)字提高為整數(shù)冪,而powf將數(shù)字提高為浮點冪。
pub fn powi(self, n: i32) -> f32pub fn powf(self, n: f32) -> f32
樓層部 (Floor Division)
In Python, we use // to find a floor division. For example 5//2=2.
在Python中,我們使用//查找底數(shù)分割。 例如5//2=2 。
Python Floor Division examples.Python Floor Division的示例。Output:
輸出:
5 // 2 is 2-5 // 2 is -3
Rust’s floating-point types use the floor method.
Rust的浮點類型使用floor方法 。
Rust Floor Division method examples.Rust Floor Division方法示例。Output:
輸出:
2-3
比較運算符 (Comparison Operators)
Python and Rust share the same symbols for all the comparison operators.
Python和Rust為所有比較運算符共享相同的符號。
Rust and Python Comparison Operators. Image by the author.Rust和Python比較運算符。 圖片由作者提供。 Rust Comparison Operators examples.Rust比較運算符示例。Output:
輸出:
a: 7, b: 4,c: 7 == 4 is false,
d: 7 != 4 is true,
e: 7<4 is false,
f: 7>4 is true,
g: 7<=7 is true,
h: 7>=7 is true
邏輯運算符 (Logical Operators)
Rust logical operator symbols are different from Python ones.
Rust邏輯運算符與Python運算符不同。
Rust and Python Logical Operators. Image by the author.Rust和Python邏輯運算符。 圖片由作者提供。 Rust Logical Operators examples.Rust邏輯運算符示例。Output:
輸出:
a: true, b: false,c: !true is false,
d: true && false is false,
e: true || false is true
按位運算符 (Bitwise Operators)
All the Rust and Python Bitwise operators share the same bitwise operator symbols except the bitwise NOT.
除按位NOT之外,所有Rust和Python按位運算符都共享相同的按位運算符。
Rust and Python Bitwise Operators. Image by the author.Rust和Python按位運算符。 圖片由作者提供。 Rust Bitwise Operators examples.Rust位運算符示例。Output:
輸出:
a: 1, b: 2,c: 1 & 2 is 0,
d: 1 | 2 is 3,
e: 1 ^ 2 is 3,
f: 1 << 2 is 4,
f2: 1 << 4 is 16,
g: 1 >> 2 is 0,
g2: 1 >> 2 is 1,
h: !1 = -2
Bitwise negation !1 returns -2. Rust uses the two’s complement to find the bitwise negation for signed types. Rust’s signed integer types are called the signed two’s complement integer types.
按位取反 !1返回-2 。 Rust使用二進制補碼來查找有符號類型的按位求反。 Rust的有符號整數(shù)類型稱為有符號二進制補碼整數(shù)類型 。
You can use 1 << n to find out exponents of 2.
您可以使用1 << n找出2的指數(shù)。
1 << n.1 << n.Output:
輸出:
2 ^ 3 = 82 ^ 4 = 16
2 ^ 5 = 32
復(fù)合分配運算符 (Compound Assignment Operators)
All the Rust and Python compound assignment operators have the same symbols except Rust doesn’t have the equivalence of power assignment **=, and floor division assignment //=.
所有Rust和Python復(fù)合賦值運算符都具有相同的符號,不同之處在于Rust不具有等效的功率分配**=和下層劃分的分配//= 。
Rust and Python Compound Assignment OperatorsRust和Python復(fù)合賦值運算符 Rust compound assignment examples.防銹化合物分配示例。Output:
輸出:
a is 21: a += 5 is 7
2: a -= 2 is 5
3: a *= 5 is 25
4: a /= 2 is 12
5: a %= 5 is 2
6: a &= 2 is 2
7: a |= 5 is 7
8: a ^= 2 is 5
9: a <<= 1 is 10
10: a >>= 2 is 2
運算符重載 (Operator Overloading)
Operator overloading is to specify more than one definition for an operator in the same scope. Python and Rust provide operator overloading. You can find Rust overloadable operators in the standard library ops module.
運算符重載是為同一范圍內(nèi)的運算符指定多個定義。 Python和Rust提供了運算符重載。 您可以在標準庫ops模塊中找到Rust重載運算符。
Rust operator overloading example.Rust運算符重載示例。Output:
輸出:
Point { x: 3, y: 3 }XOR和按位運算符真值表 (XOR and Bitwise Operators Truth Table)
As we saw previously, Python and Rust use the same symbols for bitwise symbols AND, OR , and XOR.
如前所述,Python和Rust將相同的符號用于按位符號AND , OR和XOR 。
& is the bitwise AND, | is the bitwise OR , and ^ is the bitwise XOR (exclusive OR). You can see the truth table and the Venn diagram below.
&是按位AND , | 是按位OR , ^是按位XOR(異或)。 您可以在下面看到真值表和維恩圖。
The truth table for AND, OR, and XOR.AND,OR和XOR的真值表。 AND, XOR, OR Venn diagrams與,異或或維恩圖When you use XOR with even numbers of the same number, the output is always 0.
當您將XOR與相同數(shù)字的偶數(shù)一起使用時,輸出始終為0。
In Rust, you can use {:#b} to print binary.
在Rust中,您可以使用{:#b}打印binary 。
XOR examples using Rust使用Rust的XOR示例Output:
輸出:
0 ^ 0 = 0Binary: 0 ^ 0 = 0b0
1 ^ 1 = 0
Binary: 1 ^ 1 = 0b0
2 ^ 2 = 0
Binary: 2 ^ 2 = 0b0
3 ^ 5 ^ 3 ^ 5 = 0
Binary: 3 ^ 5 ^ 3 ^ 5 = 0b0
1 ^ 1 ^ 1 = 1
Binary: 1 ^ 1 ^ 1 = 0b1
1 ^ 1 ^ 5 = 5
Binary: 1 ^ 1 ^ 5 = 0b101
You can find Python code here.
您可以在此處找到Python代碼。
問題1:單數(shù) (Problem 1: Single Number)
We are going to use this XOR to solve the LeetCoder problem called Single number.
我們將使用此XOR解決稱為單數(shù)的LeetCoder問題。
In this problem, an array input has a pair of numbers except one, for example [1, 1, 5, 5, 2]. You need to find a sing number from this array and in this case the output should be 2.
在此問題中,數(shù)組輸入具有一對數(shù)字,但一個除外,例如[1, 1, 5, 5, 2] 。 您需要從該數(shù)組中找到一個單號,在這種情況下,輸出應(yīng)為2 。
More example: When the input is [2, 2, 1], the output should be 1. When an input is [4, 1, 2, 1, 2] the output should be 4.
更多示例:輸入為[2, 2, 1] ,輸出應(yīng)為1 。 當輸入為[4, 1, 2, 1, 2] ,輸出應(yīng)為4 。
This is a good example to use the XOR operator.
這是使用XOR運算符的一個很好的例子。
Python解決方案 (Python Solution)
We briefly go through the Python solution to see how the problem was solved.
我們簡要地介紹了Python解決方案,以了解如何解決該問題。
Python solution.Python解決方案。Output:
輸出:
4Line 1: We use Python typing which is introduced from v3.5.
第1行:我們使用從v3.5引入的 Python typing 。
Line 3–4: After importing List, we create a class called Solution and method called singleNumber.
第3至4行:導(dǎo)入List ,我們創(chuàng)建一個名為Solution的類和一個名為singleNumber方法。
With Python type hints, we capitalize the name of the type, and set the name of the type inside the collection in brackets as seen above, num: List[int].
通過Python類型提示 ,我們將類型的名稱大寫,并在集合內(nèi)的類型名稱中設(shè)置括號,如上圖所示: num: List[int] 。
Line 5–8: We set a variable ans to 0. Using a for loop, we iterate the input array, nums using XOR compound assignment, ans ^= n. This will output the single number from the array.
第5–8行:我們將變量ans設(shè)置為0。使用for循環(huán),使用XOR復(fù)合賦值ans ^= n迭代輸入數(shù)組nums 。 這將從數(shù)組中輸出單個數(shù)字。
Line 10–11: We instantiate the class Solution and call the method singleNumber.
第10-11行:我們實例化類Solution并調(diào)用方法singleNumber 。
(You can run this Python code without type notations if you are interested.)
(如果您感興趣的話,可以運行此Python代碼而無需輸入類型注釋。)
The following is the solution for the LeetCode environment:
以下是LeetCode環(huán)境的解決方案:
class Solution:def singleNumber(self, nums: List[int]) -> int:
ans = 0
for n in nums:
ans ^= n
return ansPython result.Python結(jié)果。
防銹碼 (Rust Code)
Rust structs contain named fields. We use a keyword struct and set fields with its type within the curly bracket. We put methods into a impl block.
Rust 結(jié)構(gòu)包含命名字段。 我們使用關(guān)鍵字struct并在大括號內(nèi)設(shè)置其類型的字段。 我們將方法放入impl塊中。
起始碼 (Starting code)
Rust starting code.Rust起始代碼。Output:
輸出:
1Line 1: We suppress dead_code warning.
第1行:我們禁止顯示dead_code警告。
Line 2–4: Create a struct called Solution that takes one field nums with Vec<i32> type. (More on Vectors.)
2-4線:創(chuàng)建struct稱為Solution ,它有一個字段nums用Vec<i32>類型。 (有關(guān)向量的更多信息。)
Line 6–10: We create a method single_number in impl Solution. The single_number takes the first parameter &self (More on self .) and we just return 1 for now.
第6-10行:我們在impl Solution創(chuàng)建一個方法single_number 。 single_number采用第一個參數(shù)&self ( 有關(guān) self 更多信息 。),我們現(xiàn)在只返回1 。
Line 12–17: In the main function, we create an instance and print 1 using the method.
第12-17行:在main函數(shù)中,我們創(chuàng)建一個實例并使用方法打印1 。
It seems all working so we are going to complete the single_number method next.
看來一切正常,因此我們接下來將完成single_number方法。
方法和相關(guān)功能 (Method and Associated Functions)
Methods are defined within the context of a struct and their first parameter is always self, which represents the instance of the struct the method is being called on. - The Rust Programming Language
方法是在結(jié)構(gòu)的上下文中定義的,它們的第一個參數(shù)始終是self ,它表示正在調(diào)用該方法的結(jié)構(gòu)的實例。 -Rust編程語言
Associated functions don’t take self as a parameter and they are not methods because they don’t have an instance of the struct to work with.
關(guān)聯(lián)函數(shù)不以self為參數(shù),也不是方法,因為它們沒有可使用的結(jié)構(gòu)實例。
A good example is String::from function.
一個很好的例子是String::from函數(shù)。
We use the :: syntax with the struct name to call this associated function whereas we use . when we call a method.
我們使用::語法和結(jié)構(gòu)名稱來調(diào)用此關(guān)聯(lián)函數(shù),而使用. 當我們調(diào)用一個方法時。
A common associated function is a new function that returns a value of the type the associated function is associated with.
常用的關(guān)聯(lián)函數(shù)是一個new函數(shù),它返回與該關(guān)聯(lián)函數(shù)關(guān)聯(lián)的類型的值。
Rust associated function example.Rust相關(guān)功能示例。Output:
輸出:
x: 5, y: 4x: 8, y: 9
最終代碼 (Final code)
Rust final solution code.Rust最終解決方案代碼。Line 7–11: We create a mutable variable ans with the type of i32 . Using for loop, we iterate &self.nums using ans ^=n.
第7-11行:我們創(chuàng)建了一個i32類型的可變變量ans 。 使用for循環(huán),我們使用ans ^=n迭代&self.nums 。
Output:
輸出:
5We adjust the above code to the LeetCode environment.
我們將上面的代碼調(diào)整為LeetCode環(huán)境。
impl Solution {pub fn single_number(nums: Vec<i32>) -> i32 {
let mut ans: i32 = 0;
for n in nums {
ans ^= n;
}
ans
}
}Rust result in the LeetCodeLeetCode中的Rust結(jié)果
The memory usage is 2.2 MB in Rust and 16.5 MB in Python. (More on Runtime & Memory usage)
Rust的內(nèi)存使用為2.2 MB,Python的為16.5 MB。 ( 有關(guān)運行時和內(nèi)存使用的更多信息 )
使用關(guān)聯(lián)函數(shù)的解決方案 (Solution Using an Associated Function)
Since we learned about the associated function, let’s apply it to this problem.
由于我們了解了關(guān)聯(lián)的函數(shù),因此將其應(yīng)用于此問題。
Rust solution using an associated function使用關(guān)聯(lián)功能的Rust解決方案Output:
輸出:
14
Line 6–10: We create an associated function, new as we have done it before. This new function takes one parameter nums that is a vector with items of i32.
第6-10行:我們創(chuàng)建了一個關(guān)聯(lián)的函數(shù),這是我們之前做的new函數(shù)。 此new函數(shù)采用一個參數(shù)nums ,它是帶有i32項的i32 。
When the parameter names and the struct field names are exactly the same, we can use the field init shorthand syntax as nums instead of nums: nums.
當參數(shù)名稱和結(jié)構(gòu)字段名稱完全相同時,我們可以使用字段初始化速記語法作為nums而不是nums: nums 。
In the main function, we call an associated function, new and pass nums as an argument. We use method syntax to call the single_number method on the ans3 instance.
在主函數(shù)中,我們調(diào)用關(guān)聯(lián)的函數(shù)new和nums作為參數(shù)。 我們使用方法語法在ans3實例上調(diào)用single_number方法。
問題2:將數(shù)字減少為零的步驟數(shù) (Problem 2: Number of Steps to Reduce a Number to Zero)
In this problem, you input a non-negative integer num and return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
在此問題中 ,您輸入一個非負整數(shù)num并返回將其減少為零的步驟數(shù)。 如果當前數(shù)字是偶數(shù),則必須將其除以2,否則,必須從中減去1。
For example:
例如:
Input: num = 14Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.Input: num = 8
Output: 4
Explanation:
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.
This is a good example that we can use the Modulus/Remainder operator and the compound assignment operators.
這是一個很好的例子,我們可以使用“模數(shù)/余數(shù)”運算符和復(fù)合賦值運算符。
Python解決方案 (Python Solution)
Python solution on the tech.iotech.io上的Python解決方案Output:
輸出:
64
Line: 3–10: We use a while loop for num > 0. If the modulus is 0, then it must be an even number so we divide the num by 2 using a compound assignment /=2, otherwise, we subtract 1 using a compound assignment -=1. We increase the steps by 1. Finally, we return the steps.
第3-10行:對于num > 0我們使用while循環(huán)。 如果模量為0,則它??必須是偶數(shù),因此我們使用復(fù)合賦值/=2將num除以/=2 ,否則,使用復(fù)合賦值-=1減去-=1 。 我們將steps增加1。最后,我們返回steps 。
We adjust the above code to the LeetCode environment.
我們將上面的代碼調(diào)整為LeetCode環(huán)境。
class Solution:def numberOfSteps (self, num: int) -> int:
steps = 0
while num > 0:
if num % 2 == 0:
num //= 2
else:
num -=1
steps += 1
return stepsA Python result from the LeetCode.LeetCode的Python結(jié)果。
防銹解決方案 (Rust Solution)
Rust solution on tech.ioTech.io上的Rust解決方案Output:
輸出:
64
In Rust, we take the same steps as we did in Python.
在Rust中,我們采取與在Python中相同的步驟。
Line 7–16: We assign 0 to a mutable variable steps. While self.num is greater than 0, we use the compound assignment /=2 if self.num 's remainder is 0, otherwise, we subtract 1, and increase the number of step by 1.
第7-16行:我們將0分配給可變變量steps 。 當self.num大于0時,如果self.num的余數(shù)為0,則使用復(fù)合賦值/=2 ,否則,我們減去1,并將步數(shù)增加1。
We adjust the above code to the LeetCode environment.
我們將上面的代碼調(diào)整為LeetCode環(huán)境。
impl Solution {pub fn number_of_steps (mut num: i32) -> i32 {
let mut steps = 0;
while num > 0 {
if num % 2 == 0 {
num /= 2;
} else {
num -=1;
}
steps += 1;
}
steps
}
}Rust result from the LeetCodeLeetCode產(chǎn)生的銹蝕結(jié)果
結(jié)論 (Conclusion)
We learned arithmetic, comparison, logical, bitwise, and compound assignment operators in Rust. We also learned operator overloading, the difference between associated function and methods, how to use operators in Rust by converting simple Python codes to Rust.
我們在Rust中學(xué)習(xí)了算術(shù),比較,邏輯,按位和復(fù)合賦值運算符。 我們還學(xué)習(xí)了運算符重載,相關(guān)函數(shù)和方法之間的區(qū)別,如何通過將簡單的Python代碼轉(zhuǎn)換為Rust來在Rust中使用運算符。
I hope you learned something and are ready for the next step. Please stay tuned for the next post.
希望您能學(xué)到一些知識并為下一步做好準備。 請繼續(xù)關(guān)注下一篇文章。
翻譯自: https://towardsdatascience.com/a-comprehensive-tutorial-to-rust-operators-for-beginners-11554b2c64d4
rust面向?qū)ο?/p>
總結(jié)
以上是生活随笔為你收集整理的rust面向对象_面向初学者的Rust操作员综合教程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css的对号错号,也就是勾和叉
- 下一篇: Vue调试工具安装(vue devtoo