当前位置: 首页 > news >正文

从零开始学 Rust:基本概念——变量、数据类型、函数、控制流

文章目录

    • Variables and Mutability
      • Shadowing
    • Data Types
      • Scalar Types
      • Compound Types
    • Functions
      • Function Parameters
    • Comments
    • Control Flow
      • Repetition with Loops

Variables and Mutability

fn main() {let mut x = 5;println!("The value of x is: {}", x);x = 6;println!("The value of x is: {}", x);
}
fn main() {let x = 5;let x = x + 1;let x = x * 2;println!("The value of x is: {}", x);
}
  • constant: const MAX_POINTS: u32 = 100_000;

Shadowing

The other difference between mut and shadowing is that because we’re effectively creating a new variable when we use the let keyword again, we can change the type of the value but reuse the same name.

Data Types

Keep in mind that Rust is a statically typed language, which means that it must know the types of all variables at compile time.

Scalar Types

  • Integer Types

    • Signed numbers are stored using two’s complement representation.
    • Each signed variant can store numbers from − ( 2 n − 1 ) -(2^{n - 1}) (2n1) to 2 n − 1 − 1 2^{n - 1} - 1 2n11 inclusive, where n is the number of bits that variant uses. So an i8 can store numbers from − ( 2 7 ) -(2^7) (27) to 2 7 − 1 2^7 - 1 271, which equals -128 to 127. Unsigned variants can store numbers from 0 to 2 n − 1 2^n - 1 2n1, so a u8 can store numbers from 0 to 2 8 − 1 2^8 - 1 281, which equals 0 to 255.
    • The isize and usize types depend on the kind of computer your program is running on: 64 bits if you’re on a 64-bit architecture and 32 bits if you’re on a 32-bit architecture.
    • All number literals except the byte literal allow a type suffix, such as 57u8, and _ as a visual separator, such as 1_000.
    • Integer Overflow
  • Floating-Point Types

    fn main() {let x = 2.0; // f64let y: f32 = 3.0; // f32
    }
    
  • The Boolean Type

  • The Character Type

    • Rust’s char type is four bytes in size and represents a Unicode Scalar Value, which means it can represent a lot more than just ASCII.

Compound Types

  • The Tuple Type

    • Tuples have a fixed length: once declared, they cannot grow or shrink in size.

      fn main() {let tup: (i32, f64, u8) = (500, 6.4, 1);
      }
      
    • destructure by pattern matching:

      fn main() {let tup = (500, 6.4, 1);let (x, y, z) = tup;println!("The value of y is: {}", y);
      }
      
    • period(.):

      fn main() {let x: (i32, f64, u8) = (500, 6.4, 1);let five_hundred = x.0;let six_point_four = x.1;let one = x.2;
      }
      
  • The Array Type (fixed length)

    fn main() {let a = [1, 2, 3, 4, 5];
    }
    
    let a: [i32; 5] = [1, 2, 3, 4, 5];
    
    let a = [3; 5];
    
    let a = [3, 3, 3, 3, 3];
    
    • An array is a single chunk of memory allocated on the stack.
    • Invalid Array Element Access

Functions

You’ve also seen the fn keyword, which allows you to declare new functions.
Rust code uses snake case as the conventional style for function and variable names.

fn main() {println!("Hello, world!");another_function();
}fn another_function() {println!("Another function.");
}

Rust doesn’t care where you define your functions, only that they’re defined somewhere.

Function Parameters

  • 形参 parameter
  • 实参 argument
fn main() {another_function(5, 6);
}fn another_function(x: i32, y: i32) {println!("The value of x is: {}", x);println!("The value of y is: {}", y);
}
  • Statements are instructions that perform some action and do not return a value.
  • Expressions evaluate to a resulting value.
  • Statements do not return values. Therefore, you can’t assign a let statement to another variable.
fn main() {let x = 5;let y = {let x = 3;x + 1};println!("The value of y is: {}", y);
}

This expression:

{let x = 3;x + 1
}

is a block that, in this case, evaluates to 4. That value gets bound to y as part of the let statement. Note the x + 1 line without a semicolon at the end, which is unlike most of the lines you’ve seen so far. Expressions do not include ending semicolons. If you add a semicolon to the end of an expression, you turn it into a statement, which will then not return a value.

In Rust, the return value of the function is synonymous with the value of the final expression in the block of the body of a function. You can return early from a function by using the return keyword and specifying a value, but most functions return the last expression implicitly.

fn five() -> i32 {5
}fn main() {let x = five();println!("The value of x is: {}", x);
}
fn main() {let x = plus_one(5);println!("The value of x is: {}", x);
}fn plus_one(x: i32) -> i32 {x + 1
}

Comments

Control Flow

fn main() {let number = 3;if number < 5 {println!("condition was true");} else {println!("condition was false");}
}

It’s also worth noting that the condition in this code must be a bool.
Rust will not automatically try to convert non-Boolean types to a Boolean. You must be explicit and always provide if with a Boolean as its condition.

fn main() {let condition = true;let number = if condition { 5 } else { 6 };println!("The value of number is: {}", number);
}

In this case, the value of the whole if expression depends on which block of code executes. This means the values that have the potential to be results from each arm of the if must be the same type.

Repetition with Loops

  • loop
    The loop keyword tells Rust to execute a block of code over and over again forever or until you explicitly tell it to stop.

    fn main() {let mut counter = 0;let result = loop {counter += 1;if counter == 10 {break counter * 2;}};println!("The result is {}", result);
    }
    
  • while

    	fn main() {let mut number = 3;while number != 0 {println!("{}!", number);number -= 1;}println!("LIFTOFF!!!");}
    
  • for

    fn main() {let a = [10, 20, 30, 40, 50];for element in a.iter() {println!("the value is: {}", element);}
    }
    
    fn main() {for number in (1..4).rev() {println!("{}!", number);}println!("LIFTOFF!!!");
    }
    

相关文章:

从零开始学 Rust:基本概念——变量、数据类型、函数、控制流

文章目录 Variables and MutabilityShadowing Data TypesScalar TypesCompound Types FunctionsFunction Parameters CommentsControl FlowRepetition with Loops Variables and Mutability fn main() {let mut x 5;println!("The value of x is: {}", x);x 6;pri…...

记录一次SpringMVC的406错误

原生态的406错误 1. 错误起因2. 解决办法解决方式一 检查是否有导入jackson依赖解决方式二 检查web.xml中是否有配置.html 3. 再次测试 1. 错误起因 最近博主准备重新撸一遍SSM以及SpringBoot的源码&#xff0c;于是用原始的SpringMVC写了一个demo&#xff0c;并且用Tomcat进行…...

Github 2025-02-23 php开源项目日报 Top9

根据Github Trendings的统计,今日(2025-02-23统计)共有9个项目上榜。根据开发语言中项目的数量,汇总情况如下: 开发语言项目数量PHP项目9JavaScript项目2Shell项目1TypeScript项目1Blade项目1Java项目1ASP项目1Vue项目1Laravel:表达力和优雅的 Web 应用程序框架 创建周期:…...

一、初始爬虫

1.爬虫的相关概念 1.1 什么是爬虫 网络爬虫&#xff08;又被称为网页蜘蛛&#xff0c;网络机器人&#xff09;就是模拟浏览器发送网络请求&#xff0c;接收请求响应&#xff0c;一种按照一定的规则&#xff0c;自动地爬取互联网信息的程序。 原则上&#xff0c;只要是浏览器…...

《A++ 敏捷开发》- 16 评审与结对编程

客户&#xff1a;我们的客户以银行为主&#xff0c;他们很注重质量&#xff0c;所以一直很注重评审。他们对需求评审、代码走查等也很赞同&#xff0c;也能找到缺陷&#xff0c;对提升质量有作用。但他们最困惑的是通过设计评审很难发现缺陷。 我&#xff1a;你听说过敏捷的结对…...

jar、war、pom

1. <packaging>jar</packaging> 定义与用途 用途&#xff1a;默认打包类型&#xff0c;生成 JAR 文件&#xff08;Java Archive&#xff09;&#xff0c;适用于普通 Java 应用或库。 场景&#xff1a; 开发工具类库&#xff08;如 commons-lang.jar&#xff09;。…...

WSL2安装过程记录

WSL2安装过程记录 1 先决条件2 安装WSL3 安装Linux4 图形化界面 因为命令安装的时候会直接将linux发行版安装到C盘&#xff0c;对于系统盘容量小和介意不能自定义安装位置的用户来说&#xff0c;非常不友好&#xff0c;所以我这里采用手动安装的方式&#xff0c; 命令安装可以参…...

HTML列表,表格和表单

列表 在 HTML 中&#xff0c;列表&#xff08;List&#xff09;是常见的一种布局方式。列表分为两种类型&#xff1a;有序列表&#xff08;Ordered List&#xff09;和无序列表&#xff08;Unordered List&#xff09;。 无序列表 无序列表&#xff08;Unordered List&#…...

Mysql进阶篇

存储引擎 Mysql体系结构 1). 连接层 最上层是一些客户端和链接服务&#xff0c;包含本地sock 通信和大多数基于客户端/服务端工具实现的类似于TCP/IP的通信。主要完成一些类似于连接处理、授权认证、及相关的安全方案。在该层上引入了线程池的概念&#xff0c;为通过认证安全…...

Spring-JAVA

针对你的问题&#xff08;211本科、Java开发方向&#xff09;&#xff0c;以下是中级Java开发工程师的晋升时间、薪资水平及技术要求的详细说明&#xff0c;结合国内一线/二线城市现状&#xff08;数据基于2023年行业调研&#xff09;&#xff1a; 一、晋升中级开发工程师的时间…...

sql的索引与性能优化相关

之前面试的时候&#xff0c;由于在简历上提到优化sql代码&#xff0c;老是会被问到sql索引和性能优化问题&#xff0c;用这个帖子学习记录一下。 1.为什么要用索引 ------------------------------------------------------------------------------------------------------…...

【Git版本控制器】第四弹——分支管理,合并冲突,--no-ff,git stash

&#x1f381;个人主页&#xff1a;我们的五年 &#x1f50d;系列专栏&#xff1a;Linux网络编程 &#x1f337;追光的人&#xff0c;终会万丈光芒 &#x1f389;欢迎大家点赞&#x1f44d;评论&#x1f4dd;收藏⭐文章 ​ 相关笔记&#xff1a; https://blog.csdn.net/djd…...

Elasticsearch除了用作查找以外,还能可以做什么?

前言 Elasticsearch用于实时数据分析、日志存储、业务智能等。还有日志与监控、多租户和安全性。以及应用场景包括日志分析、公共数据采集、全文搜索、事件数据、数据可视化。处理错误拼写和支持变体&#xff0c;不过这些可能还是属于搜索优化。企业搜索、日志管理、应用监控、…...

Gradio全解11——使用transformers.agents构建Gradio UI(6)

大模型WebUI:Gradio全解11——使用transformers.agents构建Gradio UI(6) 前言本篇摘要11. 使用transformers.agents构建Gradio UI11.6 通过agents构建Gradio UI11.6.1 ChatMessage数据类1. 数据结构2. 例程11.6.2 构建Gradio UI示例1. 代码及运行2. 代码解读参考文献前言 本…...

自定义实现简版状态机

状态机&#xff08;State Machine&#xff09;是一种用于描述系统行为的数学模型&#xff0c;广泛应用于计算机科学、工程和自动化等领域。它通过定义系统的状态、事件和转移来模拟系统的动态行为。 基本概念 状态&#xff08;State&#xff09;&#xff1a;系统在某一时刻的特…...

算法常见八股问题整理

1.极大似然估计和交叉熵有什么关系 在分类问题中&#xff0c;当我们使用softmax函数作为输出层时&#xff0c;最大化对数似然函数实际上等价于最小化交叉熵损失函数。具体来说&#xff0c;在多分类情况下&#xff0c;最大化该样本的对数似然等价于最小化该样本的交叉熵损失。 交…...

关于GeoPandas库

geopandas buildings gpd.read_file(shapefile_path) GeoDataFrame 对象有一个属性叫做 sindex 空间索引通常是基于 R-树 或其变体构建的&#xff0c;这些数据结构专为空间查询优化&#xff0c;可以显著提高查询效率&#xff0c;尤其是在处理大型数据集时。 buildings_sin…...

【漫话机器学习系列】103.学习曲线(Learning Curve)

学习曲线&#xff08;Learning Curve&#xff09;详解 1. 什么是学习曲线&#xff1f; 学习曲线&#xff08;Learning Curve&#xff09;是机器学习和深度学习领域中用于评估模型性能随训练过程变化的图示。它通常用于分析模型的学习能力、是否存在过拟合或欠拟合等问题。 从…...

电商运营中私域流量的转化与变现:以开源AI智能名片2+1链动模式S2B2C商城小程序为例

摘要 电商运营的核心目标在于高效地将产品推向市场&#xff0c;实现私域流量的转化和变现。本文以“罗辑思维”的电商实践为背景&#xff0c;探讨了私域流量变现的重要性&#xff0c;并深入分析了开源AI智能名片21链动模式S2B2C商城小程序在电商运营中的应用与价值。通过该模式…...

Python常见面试题的详解19

1. 如何使用Django 中间件 Django 中间件宛如一个灵活且强大的插件系统&#xff0c;它为开发者提供了在请求处理流程的不同关键节点插入自定义代码的能力。这些节点包括请求抵达视图之前、视图完成处理之后以及响应即将返回给客户端之前。借助中间件&#xff0c;我们可以实现诸…...

MPNet:旋转机械轻量化故障诊断模型详解python代码复现

目录 一、问题背景与挑战 二、MPNet核心架构 2.1 多分支特征融合模块(MBFM) 2.2 残差注意力金字塔模块(RAPM) 2.2.1 空间金字塔注意力(SPA) 2.2.2 金字塔残差块(PRBlock) 2.3 分类器设计 三、关键技术突破 3.1 多尺度特征融合 3.2 轻量化设计策略 3.3 抗噪声…...

(二)TensorRT-LLM | 模型导出(v0.20.0rc3)

0. 概述 上一节 对安装和使用有个基本介绍。根据这个 issue 的描述&#xff0c;后续 TensorRT-LLM 团队可能更专注于更新和维护 pytorch backend。但 tensorrt backend 作为先前一直开发的工作&#xff0c;其中包含了大量可以学习的地方。本文主要看看它导出模型的部分&#x…...

C++ 基础特性深度解析

目录 引言 一、命名空间&#xff08;namespace&#xff09; C 中的命名空间​ 与 C 语言的对比​ 二、缺省参数​ C 中的缺省参数​ 与 C 语言的对比​ 三、引用&#xff08;reference&#xff09;​ C 中的引用​ 与 C 语言的对比​ 四、inline&#xff08;内联函数…...

OPenCV CUDA模块图像处理-----对图像执行 均值漂移滤波(Mean Shift Filtering)函数meanShiftFiltering()

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 在 GPU 上对图像执行 均值漂移滤波&#xff08;Mean Shift Filtering&#xff09;&#xff0c;用于图像分割或平滑处理。 该函数将输入图像中的…...

如何在网页里填写 PDF 表格?

有时候&#xff0c;你可能希望用户能在你的网站上填写 PDF 表单。然而&#xff0c;这件事并不简单&#xff0c;因为 PDF 并不是一种原生的网页格式。虽然浏览器可以显示 PDF 文件&#xff0c;但原生并不支持编辑或填写它们。更糟的是&#xff0c;如果你想收集表单数据&#xff…...

初探Service服务发现机制

1.Service简介 Service是将运行在一组Pod上的应用程序发布为网络服务的抽象方法。 主要功能&#xff1a;服务发现和负载均衡。 Service类型的包括ClusterIP类型、NodePort类型、LoadBalancer类型、ExternalName类型 2.Endpoints简介 Endpoints是一种Kubernetes资源&#xf…...

Python+ZeroMQ实战:智能车辆状态监控与模拟模式自动切换

目录 关键点 技术实现1 技术实现2 摘要&#xff1a; 本文将介绍如何利用Python和ZeroMQ消息队列构建一个智能车辆状态监控系统。系统能够根据时间策略自动切换驾驶模式&#xff08;自动驾驶、人工驾驶、远程驾驶、主动安全&#xff09;&#xff0c;并通过实时消息推送更新车…...

iview框架主题色的应用

1.下载 less要使用3.0.0以下的版本 npm install less2.7.3 npm install less-loader4.0.52./src/config/theme.js文件 module.exports {yellow: {theme-color: #FDCE04},blue: {theme-color: #547CE7} }在sass中使用theme配置的颜色主题&#xff0c;无需引入&#xff0c;直接可…...

Golang——9、反射和文件操作

反射和文件操作 1、反射1.1、reflect.TypeOf()获取任意值的类型对象1.2、reflect.ValueOf()1.3、结构体反射 2、文件操作2.1、os.Open()打开文件2.2、方式一&#xff1a;使用Read()读取文件2.3、方式二&#xff1a;bufio读取文件2.4、方式三&#xff1a;os.ReadFile读取2.5、写…...

day36-多路IO复用

一、基本概念 &#xff08;服务器多客户端模型&#xff09; 定义&#xff1a;单线程或单进程同时监测若干个文件描述符是否可以执行IO操作的能力 作用&#xff1a;应用程序通常需要处理来自多条事件流中的事件&#xff0c;比如我现在用的电脑&#xff0c;需要同时处理键盘鼠标…...