学习Rust的第4天:常见编程概念

基于Steve Klabnik的《The Rust Programming Language》一书。昨天我们做了一个猜谜游戏 ,今天我们将探讨常见的编程概念,例如:

  • Variables 变量
  • Constants 常数
  • Shadowing 阴影
  • Data Types 数据类型
  • Functions 功能

Variables 变量

In layman terms, Variables are like container that store a value. Let’s just take a quick look at them
通俗地说,变量就像存储值的容器。让我们快速的看一下

  • Variables can store different types of values such as : numbers, text or complex structures
    变量可以存储不同类型的值,例如:数字、文本或复杂结构
  • Each variable has a name
    每个变量都有一个名称
  • In rust a variable is immutable by default, meaning the value cannot be change once set, to make a variable mutable mut keyword is used.
    在rust中,变量默认是不可变的,这意味着一旦设置了值就不能改变,要使变量可变,使用 mut 关键字。
  • You can explicitly define what type of value is going to be stored in a variable but it is optional.
    你可以显式定义什么类型的值将被存储在变量中,但它是可选的。
  • Variables have a limited scope, meaning they can only be accessed in a certain portion of the code
    变量的作用域有限,这意味着只能在代码的某个部分访问它们

Example : 范例:

fn main(){let x = 10; //immutable varlet mut y = 15; //mutable varprintln!("X = {}",x);println!("Y = {}",y);y = 2println!("X = {}",x);println!("Y = {}",y);
}

Constants 常数

Like immutable variables, constants are values that are not allowed to change, but there are a few differences
与不可变变量一样,常量是不允许更改的值,但也有一些不同之处

  • Constants are inherently immutable, mut keyword cannot be used with them
    常量本质上是不可变的, mut 关键字不能与它们一起使用
  • They are initialized at the time of compilation, compile-time initialization
    它们在编译时初始化,编译时初始化
  • Constants have a global scope and can be accessed from anywhere in the program
    常量具有全局作用域,可以从程序中的任何位置访问
  • Type definition is required for constants
    常量需要类型定义

Example : 范例:

const VALUE_OF_PI: u32 = 3.1418;

Shadowing 阴影

As we saw yesterday, with shadowing you can declare a new variable with the same name as the previous variable and the newer variable will overshadow the previous one
正如我们昨天所看到的,使用阴影,您可以声明一个与前一个变量同名的新变量,并且新变量将覆盖前一个变量

Example : 范例:

fn main(){let x = 10;let x = x - 7;{let x = x * 2;println!("X in inner scope = {}",x);}println!("X in oouter scope = {}",x);
}

Output : 输出量:

$ cargo run
X in inner scope = 6
X in outer scope = 3

Data Types 数据类型

Data types can further be divided into two groups: Scalar and Compound data types
数据类型可以进一步分为两组:标量和复合数据类型

Scalar Data Types 标量数据类型

A scalar type represents one value, Rust has 4 primary Scalar data types:
标量类型代表一个值,Rust有4种主要的标量数据类型:

Integer 整数

An integer is a number without the fractional component, We used it yesterday in the guessing game, u32 means an unsigned 32 bit integer
整数是一个没有小数部分的数字,我们昨天在猜谜游戏中使用了它, u32 表示无符号的32位整数

Other types of integer include :
其他类型的整数包括:

Signed : 签署人:

  • The difference between a signed and an unsigned integer is whether the number needs to have a sign or whether it will only be positive
    有符号整数和无符号整数之间的区别在于数字是否需要有一个 sign ,或者它是否只会是正数
  • Each signed integer can store numbers from -(2^(n — 1)) to (2^(n — 1)) — 1, Where n = the number of bits the variant uses
    每个有符号整数可以存储从-(2^(n - 1))到(2^(n - 1))- 1的数字,其中n =变体使用的位数
  • Example : i8, i16, i32, i64, i128
    示例:i8、i16、i32、i64、i128

Unsigned : 未签名:

  • Unsigned numbers are always positive.
    无符号数总是正数。
  • Each unsigned integer can store numbers from 0 to 2^n — 1
    每个无符号整数可以存储从0到 2^n — 1 的数字
  • Example : u8, u16, u32, u64, u128
    示例:u8、u16、u32、u64、u128

Additionally there is isize and usize depend on the architecture of the computer the program is running on. 32 bits if the program is running on 32 bit architecture and 64 bits if the program is running on 64 bit architecture
此外,还有 isize 和 usize 取决于程序运行的计算机的架构。如果程序运行在32位架构上,则为32位,如果程序运行在64位架构上,则为64位

Integer Overflow: 溢出:

  • Computers represent integers using a fixed number of bits, determining the range they can cover.
    计算机使用固定的位数来表示整数,确定它们可以覆盖的范围。
  • In Rust, when the result of an arithmetic operation exceeds the maximum representable value for a data type (overflow), it wraps around to the minimum value and continues counting.
    在Rust中,当算术运算的结果超过数据类型的最大可表示值(溢出)时,它会返回到最小值并继续计数。

Example of Integer overflow:
内存溢出示例:

If you’re using an 8-bit integer, the range is 0 to 255. If you try to add 1 to 255, in normal arithmetic, you’d expect 256. However, in Rust, it wraps around to 0 due to overflow.
如果使用8位整数,则范围为0到255。如果你试着把1加到255,在正常的算术中,你会得到256。然而,在Rust中,由于溢出,它会返回到0。

Floating-point numbers : 浮点数:

Floating point numbers in rust have a fractional component. Unlike integers Floating-point numbers are always signed. There are two types of floating-point numbers : f32 and f64 32 and 64 representing the size in bits.
rust中的浮点数有一个小数部分。与整数不同,浮点数总是有符号的。有两种类型的浮点数: f32 和 f64 32和64表示位的大小。

Example : 范例:

fn main() {// Using f32let float_32: f32 = 3.14; // A 32-bit floating-point numberprintln!("f32 value: {}", float_32);// Using f64let float_64: f64 = 3.141592653589793; // A 64-bit floating-point numberprintln!("f64 value: {}", float_64);// Performing arithmetic operationslet result_f32 = float_32 * 2.0;let result_f64 = float_64 * 2.0;// Displaying resultsprintln!("Result (f32): {}", result_f32);println!("Result (f64): {}", result_f64);
}

Numeric operations 数值运算

Rust supports the basic mathematical operations such as :
Rust支持基本的数学运算,例如:

  • Addition 此外
  • Subtraction 减法
  • Multiplication 乘法
  • Division 司
  • Modulus 模量

Example: 范例:

fn main(){let sum = 10+7;let subtraction = 60-4;let multilpication = 7 * 7;let division = 25/5;let modulus = 13%2;println!("10 + 7 = {}",sum);println!("60 - 4 = {}",subtraction);println!("7 * 7 = {}",multilpication);println!("25 / 5= {}",division);println!("13 % 2= {}",modulus);
}

Boolean Type 布尔类型

As in most programming languages, a boolean type is one byte in size and can be either true or false.
与大多数编程语言一样,布尔类型的大小是一个字节,可以是 true 或 false 。

Example: 范例:

fn main(){let t = true;let f: bool = false;
}

Character type 字符类型

Rust’s char type is the most primitive alphabetic type, similar to char in C.
Rust的char类型是最原始的字母类型,类似于C中的 char 。

fn main(){let z = 'Z';let x: char = "X";
}

Side note : Characters are enclosed in single quotes, and Strings are enclosed in double quotes.
旁注:字符用单引号括起来,字符串用双引号括起来。

Compound Types 复合类型

Compound types can store multiple values in one type. They are often group of scalar data.
复合类型可以在一个类型中存储多个值。它们通常是一组标量数据。

Tuple 元组

A tuple in Rust is like a mixed bag that can hold different types of items, allowing you to group and organize them in a specific order. It’s a simple way to bundle multiple values together.
Rust中的元组就像一个混合的袋子,可以容纳不同类型的项目,允许您以特定的顺序对它们进行分组和组织。这是一种将多个值捆绑在一起的简单方法。

Tuples are immutable. However, the elements within the tuple may be mutable if they are declared as mutable variables.
元组不可变。但是,如果元组中的元素被声明为可变变量,则它们可能是可变的。

Syntax 语法

let var_name: (data_type1,data_type2...data_typeN) = (val1,val2...valN);//The values in this tuple is mutable
let mut var_name: (data_type1,data_type2...data_typeN) = (val1,val2...valN);

Example 例如

let tup: (i32, f64, u16) = (500,3.141,9);

Accessing data in tuples 将数据存储在元组中

Indexing: 索引:

Indexing is the act of accessing a specific element in a data structure, like an array or tuple, using its position or key.
索引是访问数据结构中特定元素的行为,如数组或元组,使用其位置或键。

To access a tuple using indexing we can do this:
要使用索引访问元组,我们可以这样做:

println!("{}",tuple_name.index);

Example: 范例:

fn main() {// Creating a tuplelet my_tuple = (42, "hello", 3.14);// Accessing elements using indexing (zero-based)let first_element = my_tuple.0;   // Access the first element (42)let second_element = my_tuple.1;  // Access the second element ("hello")let third_element = my_tuple.2;   // Access the third element (3.14)// Printing the accessed elementsprintln!("First element: {}", first_element);println!("Second element: {}", second_element);println!("Third element: {}", third_element);
}

Array 阵列

Arrays are another way to store data of the same type, sequentially. Arrays in rust have a fixed length.
数组是按顺序存储相同类型数据的另一种方式。rust中的数组有固定的长度。

To write an array we use square brackets [] as a comma-seperated list.
为了写一个数组,我们使用方括号 [] 作为逗号分隔的列表。

Example: 范例:

fn main(){let a: [i32;5]= [1,2,3,4,5];
}

We can also do this :
我们也可以这样做:

fn main(){let x = [6; 4]; // [6,6,6,6]
}

Accessing array elements:
数组元素:

fn main() {let a: [u32; 6] = [1, 2, 3, 4, 5, 6];let first: u32 = a[0];let last: u32 = a[a.len() - 1];println!("First element : {}", first); // 1println!("Last element : {}", last); // 6
}

Functions 功能

Technically the definition of a functions is, a self-contained unit of code that performs a specific task, taking inputs and producing outputs, enhancing code structure and reusability.
从技术上讲,函数的定义是一个独立的代码单元,它执行特定的任务,接受输入并产生输出,增强代码结构和可重用性。

The main function is the entry point of a rust porgram, similarly we can use the fn keyword to declare custom functions that perform a specific task.
main 函数是rust程序的入口点,同样,我们可以使用 fn 关键字来声明执行特定任务的自定义函数。

In rust snake_case is the convention for declaring functions and variable names.
在rust中, snake_case 是声明函数和变量名的约定。

Example 例如

fn main(){println!("The main Function");new_function();
}fn new_function(){println!("This is a custom function");
}

Output 输出

$ cargo run
The main Function
This is a custom function

Parameters 参数

In layman’s terms : A parameter is an input passed to a function
通俗地说:参数是传递给函数的输入

Technically, Parameters are a function’s placeholders in its definition and arguments are the actual values or data you provide to a function when you call it. They match the parameters’ types and order defined in the function.
从技术上讲,参数是函数定义中的占位符,参数是调用函数时提供给函数的实际值或数据。它们与函数中定义的参数类型和顺序相匹配。

Although people do tend to use these words interchangeably.
尽管人们倾向于互换使用这些词。

Example 例如

fn main(){println!("The main Function");addition(5,9);
}
fn addition(x: i32,y: i32){println!("Addition of {} + {} = {}",x,y,x+y);
}

Output 输出

$ cargo run
The main Function
Addition of 5 + 9 = 14

Statements and expressions
语句和表达式

Statements are instruction that perform a certain task, Whereas Expressions evaluate to a value.
语句是执行特定任务的指令,而表达式的计算结果是一个值。

Example 例如

fn main(){let y = 6; //Statementlet x = 5; //Statementlet result = x+y; // here "x+y" is an expression
}

Functions with return values
返回值函数

Functions can return a value when they are called . We must declare the return type of a function with an arrow ->
函数在被调用时可以返回一个值。我们必须用箭头声明函数的返回类型 ->

In rust, The final expression of the function is the return value of the function.
在rust中,函数的最终表达式是函数的返回值。

Example 例如

fn main(){println!("The main Function");let sum = addition(5,9);println!("Result of the function : {}", sum);
}
fn addition(x: i32,y: i32) -> i32 {x+y // The return statement
}

In Rust, the absence of a semicolon at the end of a return statement indicates that it is the value to be returned, making the code more explicit and reducing redundancy.
在Rust中,return语句末尾没有一个numberon表示它是要返回的值,使代码更加明确并减少冗余。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/822518.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C语言入门第四天(数组)

一、C语言数组的基本语法 1.数组的定义 数组是 C 语言中的一种数据结构,用于存储一组具有相同数据类型的数据。数组中的每个元素可以通过一个索引(下标)来访问,索引从 0 开始,最大值为数组长度减 1。 2.定义语法格式 …

【鸿蒙开发】动画

1. 属性动画 animation放在其他属性的后面才有过渡效果 组件的某些通用属性变化时,可以通过属性动画实现渐变过渡效果,提升用户体验。支持的属性包括width、height、backgroundColor、opacity、scale、rotate、translate等。 接口: animati…

4个步骤:如何使用 SwiftSoup 和爬虫代理获取网站视频

摘要/导言 在本文中,我们将探讨如何使用 SwiftSoup 库和爬虫代理技术来获取网站上的视频资源。我们将介绍一种简洁、可靠的方法,以及实现这一目标所需的步骤。 背景/引言 随着互联网的迅速发展,爬虫技术在今天的数字世界中扮演着越来越重要…

Python也可以合并和拆分PDF,批量高效!

PDF是最方便的文档格式,可以在任何设备原样且无损的打开,但因为PDF不可编辑,所以很难去拆分合并。 知乎上也有人问,如何对PDF进行合并和拆分? 看很多回答推荐了各种PDF编辑器或者网站,确实方法比较多。 …

支持向量机模型pytorch

通过5个条件判定一件事情是否会发生,5个条件对这件事情是否发生的影响力不同,计算每个条件对这件事情发生的影响力多大,写一个支持向量机模型pytorch程序,最后打印5个条件分别的影响力。 示例一 支持向量机(SVM)是一种…

【原创】springboot+mysql理发会员管理系统设计与实现

个人主页:程序猿小小杨 个人简介:从事开发多年,Java、Php、Python、前端开发均有涉猎 博客内容:Java项目实战、项目演示、技术分享 文末有作者名片,希望和大家一起共同进步,你只管努力,剩下的交…

c++中虚函数、纯虚函数以及虚函数的实现原理

c中虚函数、纯虚函数以及虚函数的实现原理 什么是虚函数和纯虚函数 虚函数(Virtual Functions)和纯虚函数(Pure Virtual Functions)是 C 中用于实现多态性的重要概念。 虚函数(Virtual Functions) 虚函…

算法课程笔记——常用库函数

memset初始化 设置成0是可以每个设置为0 而1时会特别大 -1的补码是11111111 要先排序 unique得到的是地址 地址减去得到下标 结果会放到后面 如果这样非相邻 会出错 要先用sort排序 O(n)被O(nlogn)覆盖

服务器数据恢复—xfs文件系统节点、目录项丢失的数据恢复案例

服务器数据恢复环境: EMC某型号存储,该存储内有一组由12块磁盘组建的raid5阵列,划分了两个lun。 服务器故障: 管理员为服务器重装操作系统后,发现服务器的磁盘分区发生改变,原来的sdc3分区丢失。由于该分区…

photoshop基础学习笔记

学习 Photoshop 的基础知识是掌握图像处理和设计的关键。以下是一份基础学习笔记,帮助你开始学习 Photoshop: 1. Photoshop 界面导览 工具栏(Tool Bar):包含了各种工具,如选择工具、画笔工具、橡皮擦工具…

Linux命令学习—DHCP 服务器

1.1、DHCP 服务器 ①、DHCP(dynamic host configure protocol)动态主机配置协议 最大的功能就是向客户端提供 TCP/IP 信息,使用的是 UDP:67 端口 ②、手动设定适合:适用小型网络 ③、手动输入 IP 地址和自动获取比较优缺点 ④…

攻防演练,作为红方的步骤应该是那些

在执行合法的攻防演练中,对目标服务器如 http://XXXXX/ 进行漏洞扫描和评估需要遵循严格的步骤来确保所有活动都是安全、合法且有效的。以下是一些基本步骤和技术指南,以及使用 nmap 进行初始扫描的示例。 1. 获取授权 确保你有明确的书面授权来进行漏…

问,由于java存在性能上,以及部分功能上的缺点,请问如何正确使用C,C++,Go,这三个语言,提升Java Web项目的性能?

拓展阅读:版本任你发,我用java8 我明白Java虽然在许多方面表现出色,但在某些特定场景下可能会遇到性能瓶颈或功能限制。为了提升Java Web项目的性能,可以考虑将C、C和Go这三种语言用于特定的组件或服务。以下是如何正确使用这些语…

葡萄书--深度学习基础

卷积神经网络 卷积神经网络具有的特性: 平移不变性(translation invariance):不管检测对象出现在图像中的哪个位置,神经网络的前面几层应该对相同的图像区域具有相似的反应,即为“平移不变性”。图像的平移…

设置Linux命令行tab补全不区分大小写

root权限编辑文件 sudo vim /etc/inputrc加入新配置 [按下i键开始输入] 文件末尾加入新配置 set completion-ignore-case on保存 [按下esc键,再输入:wq确定保存] 重启 reboot

web自动化系列-selenium 的鼠标操作(十)

对于鼠标操作 ,我们可以通过click()方法进行点击操作 ,但是有些特殊场景下的操作 ,click()是无法完成的 ,比如 :我想进行鼠标悬停 、想进行鼠标拖拽 ,怎么办 ? 这个时候你用click()是无法完成的…

渲染技术如何改变影视制作的面貌

随着科技的飞速发展,影视制作领域也迎来了翻天覆地的变化。其中,渲染技术的不断革新,更是对影视制作产生了深远的影响。渲染作为影视制作中的关键环节,渲染技术的提升,不仅提升了画面的质量,还为创作者提供…

计算机网络 Cisco远程Telnet访问交换机和Console终端连接交换机

一、实验要求和内容 1、配置交换机进入特权模式密文密码为“abcd两位班内学号”,远程登陆密码为“123456” 2、验证PC0通过远程登陆到交换机上,看是否可以进去特权模式 二、实验步骤 1、将一台还没配置的新交换机,利用console线连接设备的…

Github 2024-04-17 C开源项目日报Top10

根据Github Trendings的统计,今日(2024-04-17统计)共有10个项目上榜。根据开发语言中项目的数量,汇总情况如下: 开发语言项目数量C项目10C++项目2Whisper.cpp: 高性能自动语音识别模型的C/C++移植 创建周期:569 天开发语言:C, C++协议类型:MIT LicenseStar数量:30141 个…

Spark大数据常见错误及解决方案-HDFS-费元星

为什么一直鼓励大家做好错误记录,因为人脑的遗忘性是固定的,知识密集型的点,随着时间流逝,都会逐步遗忘掉。 另外鼓励大家对每个知识点都先去源码里搜一下。有几个点非常重要: 1.源码中的错误提示是非常系统的&#x…