当前位置: 首页 > 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;我们可以实现诸…...

SciencePlots——绘制论文中的图片

文章目录 安装一、风格二、1 资源 安装 # 安装最新版 pip install githttps://github.com/garrettj403/SciencePlots.git# 安装稳定版 pip install SciencePlots一、风格 简单好用的深度学习论文绘图专用工具包–Science Plot 二、 1 资源 论文绘图神器来了&#xff1a;一行…...

汽车生产虚拟实训中的技能提升与生产优化​

在制造业蓬勃发展的大背景下&#xff0c;虚拟教学实训宛如一颗璀璨的新星&#xff0c;正发挥着不可或缺且日益凸显的关键作用&#xff0c;源源不断地为企业的稳健前行与创新发展注入磅礴强大的动力。就以汽车制造企业这一极具代表性的行业主体为例&#xff0c;汽车生产线上各类…...

鸿蒙中用HarmonyOS SDK应用服务 HarmonyOS5开发一个医院挂号小程序

一、开发准备 ​​环境搭建​​&#xff1a; 安装DevEco Studio 3.0或更高版本配置HarmonyOS SDK申请开发者账号 ​​项目创建​​&#xff1a; File > New > Create Project > Application (选择"Empty Ability") 二、核心功能实现 1. 医院科室展示 /…...

linux 错误码总结

1,错误码的概念与作用 在Linux系统中,错误码是系统调用或库函数在执行失败时返回的特定数值,用于指示具体的错误类型。这些错误码通过全局变量errno来存储和传递,errno由操作系统维护,保存最近一次发生的错误信息。值得注意的是,errno的值在每次系统调用或函数调用失败时…...

2025 后端自学UNIAPP【项目实战:旅游项目】6、我的收藏页面

代码框架视图 1、先添加一个获取收藏景点的列表请求 【在文件my_api.js文件中添加】 // 引入公共的请求封装 import http from ./my_http.js// 登录接口&#xff08;适配服务端返回 Token&#xff09; export const login async (code, avatar) > {const res await http…...

Java求职者面试指南:Spring、Spring Boot、MyBatis框架与计算机基础问题解析

Java求职者面试指南&#xff1a;Spring、Spring Boot、MyBatis框架与计算机基础问题解析 一、第一轮提问&#xff08;基础概念问题&#xff09; 1. 请解释Spring框架的核心容器是什么&#xff1f;它在Spring中起到什么作用&#xff1f; Spring框架的核心容器是IoC容器&#…...

Go 并发编程基础:通道(Channel)的使用

在 Go 中&#xff0c;Channel 是 Goroutine 之间通信的核心机制。它提供了一个线程安全的通信方式&#xff0c;用于在多个 Goroutine 之间传递数据&#xff0c;从而实现高效的并发编程。 本章将介绍 Channel 的基本概念、用法、缓冲、关闭机制以及 select 的使用。 一、Channel…...

【Redis】笔记|第8节|大厂高并发缓存架构实战与优化

缓存架构 代码结构 代码详情 功能点&#xff1a; 多级缓存&#xff0c;先查本地缓存&#xff0c;再查Redis&#xff0c;最后才查数据库热点数据重建逻辑使用分布式锁&#xff0c;二次查询更新缓存采用读写锁提升性能采用Redis的发布订阅机制通知所有实例更新本地缓存适用读多…...

CSS | transition 和 transform的用处和区别

省流总结&#xff1a; transform用于变换/变形&#xff0c;transition是动画控制器 transform 用来对元素进行变形&#xff0c;常见的操作如下&#xff0c;它是立即生效的样式变形属性。 旋转 rotate(角度deg)、平移 translateX(像素px)、缩放 scale(倍数)、倾斜 skewX(角度…...

LabVIEW双光子成像系统技术

双光子成像技术的核心特性 双光子成像通过双低能量光子协同激发机制&#xff0c;展现出显著的技术优势&#xff1a; 深层组织穿透能力&#xff1a;适用于活体组织深度成像 高分辨率观测性能&#xff1a;满足微观结构的精细研究需求 低光毒性特点&#xff1a;减少对样本的损伤…...