Rust语言基础语法

文章目录

  • 一、让程序跑起来
  • 二、常量和变量
    • 1.常量
    • 2.变量
  • 三、数据类型
  • 四、条件判断
    • 1.if语句
    • 2.match语句
  • 五、循环语句
    • 1.loop 无条件循环
    • 2.while 条件循环
    • 3.for 集合遍历


Rust程序设计语言-官方文档

一、让程序跑起来

使用cargo创建一个项目,输出hello,world!

$cargo new hello# hello.rs
fn main() {println!("Hello, world!");
}
------------------
$cargo run helloCompiling hello v0.1.0 (D:\RustPro\hello)Finished dev [unoptimized + debuginfo] target(s) in 1.39sRunning `target\debug\hello.exe hello`
Hello, world!

二、常量和变量

rust语言和其他语言一样,也分常量和变量

  • 常亮就是一直不变的,程序中不可以更改,使用const 进行定义
  • 变量就是可变量,在Rust中分为可变变量和不可变变量
    • 不可变变量使用 let 进行定义
      -可变变量使用 let mut 进行定义

1.常量

# 正确使用
fn main() {const MAX_POINTS: u32 = 100_000;println!("{}",MAX_POINTS);
}
输出:100000# 错误使用,在程序中修改常量
fn main() {const MAX_POINTS: u32 = 100_000;MAX_POINTS = 200_000;println!("{}",MAX_POINTS);
}
$cargo run helloCompiling hello v0.1.0 (D:\RustPro\hello)
error[E0070]: invalid left-hand side of assignment--> src\main.rs:3:16|
3 |     MAX_POINTS = 200_000;|     ---------- ^|     ||     cannot assign to this expressionFor more information about this error, try `rustc --explain E0070`.
error: could not compile `hello` (bin "hello") due to previous error

2.变量

# 不可变变量在程序中无法修改
fn main() {let mut x:i64 = 6;println!("{}",x);x = 7;println!("{}",x);
}$cargo run helloCompiling hello v0.1.0 (D:\RustPro\hello)
error[E0384]: cannot assign twice to immutable variable `x`--> src\main.rs:4:5|
2 |     let x:i64 = 6;|         -|         ||         first assignment to `x`|         help: consider making this binding mutable: `mut x`
3 |     println!("{}",x);
4 |     x = 7;|     ^^^^^ cannot assign twice to immutable variableFor more information about this error, try `rustc --explain E0384`.
error: could not compile `hello` (bin "hello") due to previous error
# 应该使用可变变量
fn main() {let mut x:i64 = 6;println!("{}",x);x = 7;println!("{}",x);
}
$cargo run helloCompiling hello v0.1.0 (D:\RustPro\hello)Finished dev [unoptimized + debuginfo] target(s) in 0.32sRunning `target\debug\hello.exe hello`
6
7

三、数据类型

Rust 是 静态类型(statically typed)语言,也就是说在编译时就必须知道所有变量的类型。

与其他语言一样,Rust也有整型、浮点型、字符串、布尔型等数据类型,由于整型变量定义不规范容易造成溢出,所以单列一个表。另外在Rust语言中f32代表单精度,f64代表双精度

长度有符号无符号
8-biti8u8
16-biti16u16
32-biti32u32
64-biti64u64
128-biti128u128
archisizeusize

四、条件判断

1.if语句

与其他变成语言一样,单条件判断、多条件分支都可以。

# 多条件分支
fn main() {let x:i64 = 6;if x > 6{println!(">6");}else if x==6{println!("=6");}else {println!("<6");}
}
$cargo run helloCompiling hello v0.1.0 (D:\RustPro\hello)Finished dev [unoptimized + debuginfo] target(s) in 0.74sRunning `target\debug\hello.exe hello`
=6

其他的条件判断语句按照以上例子拆解,不在赘述

2.match语句

match语句,它与其他编程语言中的switch或case语句相似,但功能更为强大和灵活。

fn main() {  let number = 3;  match number {  1 => println!("One"),  2 => println!("Two"),  3 => println!("Three"),  _ => println!("Another number"), // _ 是一个通配符,匹配所有其他情况  }  
}
$cargo run helloCompiling hello v0.1.0 (D:\RustPro\hello)Finished dev [unoptimized + debuginfo] target(s) in 0.35sRunning `target\debug\hello.exe hello`
Three

五、循环语句

在Rust语言中,提供了三种循环语句

  • loop 无条件循环
  • while 条件循环
  • for 集合遍历

1.loop 无条件循环

  • 由于loop是无条件循环语句,所以必须在循环内部加判断结束的语句,否则造成死循环。
  • 使用break进行返回,可以携带返回值,可以跳转指定标签位置。
# break 携带返回值
fn main() {let mut counter = 0;let result = loop {counter += 1;if counter == 10 {break counter * 2;}};println!("The result is {result}");
}
$cargo run helloCompiling hello v0.1.0 (D:\RustPro\hello)Finished dev [unoptimized + debuginfo] target(s) in 0.36sRunning `target\debug\hello.exe hello`
The result is 20# loop多重循环,break 跳转指定标签
fn main() {let mut count = 0;'counting_up: loop {println!("count = {count}");let mut remaining = 10;loop {println!("remaining = {remaining}");if remaining == 9 {break;}if count == 2 {break 'counting_up;}remaining -= 1;}count += 1;}println!("End count = {count}");
}
$cargo run helloCompiling hello v0.1.0 (D:\RustPro\hello)Finished dev [unoptimized + debuginfo] target(s) in 0.35sRunning `target\debug\hello.exe hello`
count = 0
remaining = 10
remaining = 9
count = 1
remaining = 10
remaining = 9
count = 2
remaining = 10
End count = 2

2.while 条件循环

与其他语言条件循环没有区别

# 输出100以内斐波那契数列
fn main() {let mut a = 0;let mut b = 1;let mut c = 1;while c < 100 {println!("{}",c);c = a+b;a=b;b=c;}
}
$cargo run helloCompiling hello v0.1.0 (D:\RustPro\hello)Finished dev [unoptimized + debuginfo] target(s) in 0.36sRunning `target\debug\hello.exe hello`
1
1
2
3
5
8
13
21
34
55
89

3.for 集合遍历

需要注意的是遍历的时候,需要的是集合下标还是集合的值。

# 单遍历集合值
fn main() {let a = [10, 20, 30, 40, 50];for element in a {println!("the value is: {element}");}
}
$cargo run helloCompiling hello v0.1.0 (D:\RustPro\hello)Finished dev [unoptimized + debuginfo] target(s) in 0.36sRunning `target\debug\hello.exe hello`
the value is: 10
the value is: 20
the value is: 30
the value is: 40
the value is: 50
# 同时遍历集合下标和值
fn main() {  let arr = [10, 20, 30, 40, 50];  for (index, value) in arr.iter().enumerate() {  println!("Index: {}, Value: {}", index, value);  }  
}
$cargo run helloCompiling hello v0.1.0 (D:\RustPro\hello)Finished dev [unoptimized + debuginfo] target(s) in 0.39sRunning `target\debug\hello.exe hello`
Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
Index: 3, Value: 40
Index: 4, Value: 50

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

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

相关文章

CTF-WEB进阶与学习

PHP弱类型 在进行比较的时候&#xff0c;会先判断两种字符串的类型是否相等&#xff0c;再比较 在进行比较的时候&#xff0c;会先将字符串类型转化成相同&#xff0c;再比较 如果比较一个数字和字符串或者比较涉及到数字内容的字符串&#xff0c;则字符串会被转换成数值 并且…

FFmpge命令记录

日常开发中会用到FFmpeg进行编解码和视频呈现、视频推流&#xff0c;现将平时工作中用到的几个命令做一下记录&#xff0c;以备不时之需&#xff1a; 1.选定网卡&#xff0c;接受组播 // 【命令行】指定本地ip为192.168.70.61的网卡用来接收数据 ffmpeg -localaddr 192.168.7…

SpringBoot连接SqlServer出现的问题

“Encrypt”属性设置为“true”且 “trustServerCertificate”属性设置为“false”&#xff0c;但驱动程序无法使用安全套接字层 (SSL) 加密与 SQL Server 建立安全连接:错误:PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable …

c语言游戏实战(3):三子棋

前言&#xff1a; 三子棋是一种民间传统游戏&#xff0c;又叫九宫棋、圈圈叉叉棋、一条龙、井字棋等。游戏规则是双方对战&#xff0c;双方依次在9宫格棋盘上摆放棋子&#xff0c;率先将自己的三个棋子走成一条线就视为胜利。但因棋盘太小&#xff0c;三子棋在很多时候会出现和…

人工智能|深度学习——基于全局注意力的改进YOLOv7-AC的水下场景目标检测系统

代码下载&#xff1a; 基于全局注意力的改进YOLOv7-AC的水下场景目标检测系统.zip资源-CSDN文库 1.研究的背景 水下场景目标检测是水下机器人、水下无人机和水下监控等领域中的重要任务之一。然而&#xff0c;由于水下环境的复杂性和特殊性&#xff0c;水下目标检测面临着许多挑…

计算机网络——新型网络架构:SDN/NFV

1. 传统节点与SDN节点 1.1 传统节点(Traditional Node) 这幅图展示了传统网络节点的结构。在这种设置中&#xff0c;控制层和数据层是集成在同一个设备内。 以太网交换机&#xff1a;在传统网络中&#xff0c;交换机包括控制层和数据层&#xff0c;它不仅负责数据包的传输&…

编译spring原码

1.下载原码 spring原码下载地址链接: github地址 最好选择一个release版本&#xff0c;毕竟发布版稳定&#xff0c;上述连接指向的是5.2.0 release 2.配置gradle 由于spring源码是用gradle管理的。为了能顺利得下载项目所需的jar包&#xff0c;因此要先配置一下gradle&#xff…

docker安装zpan

安装 1.创建数据库 docker run -di --namezpan_mysql -p 3309:3306 -e MYSQL_ROOT_PASSWORD123456 mysql 2.手动新建数据库zpan 3.创建目录 mkdir -p /opt/zpan cd /opt/zpan 4.编写配置文件 vim config.yml #详细配置文档可参考&#xff1a; https://zpan.space/#/zh…

机器学习之DeepSequence软件使用学习1

简介 DeepSequence 是一个生成性的、无监督的生物序列潜变量模型。给定一个多重序列比对作为输入&#xff0c;它可以用来预测可获得的突变&#xff0c;提取监督式学习的定量特征&#xff0c;并生成满足明显约束的新序列文库。它将序列中的高阶依赖性建模为残差子集之间约束的非…

2024/2/6学习记录

ts 因为已经学习过了 js &#xff0c;下面的都是挑了一些 ts 与 js 不同的地方来记录。 安装 npm install -g typescript 安装好之后&#xff0c;可以看看自己的版本 ts基础语法 模块 函数 变量 语法和表达式 注释 编译 ts 文件需要用 tsc xxx.ts &#xff0c;js 文件…

css鼠标悬浮动效

展示效果图 css样式 完整代码复制体验&#xff08;图片就不提供了&#xff0c;自己随便找一些&#xff09; 模板部分 里面的事件只是为了做路由的跳转&#xff0c;就不展示出来了 <div class"canvas-main"><div class"all" mouseover"hid…

《计算机网络简易速速上手小册》第8章:软件定义网络(SDN)与网络功能虚拟化(NFV)(2024 最新版)

第8章&#xff1a;软件定义网络&#xff08;SDN&#xff09;与网络功能虚拟化&#xff08;NFV&#xff09; 文章目录 8.1 SDN 架构与原理 - 智能网络的构建积木8.1.1 基础知识8.1.2 重点案例&#xff1a;使用 Python 控制 OpenFlow 交换机准备工作Python 脚本示例 8.1.3 拓展案…

C++ STL精通之旅:向量、集合与映射等容器详解

目录 常用容器 顺序容器 向量vector 构造 尾接 & 尾删 中括号运算符 获取长度 清空 判空 改变长度 提前分配好空间 代码演示 运行结果 关联容器 集合set 构造 遍历 其他 代码演示 运行结果​编辑 映射map 常用方法 构造 遍历 其他 代码演示1​编…

【VSTO开发-WPS】下调试

重点2步&#xff1a; 1、注册表添加 Windows Registry Editor Version 5.00[HKEY_CURRENT_USER\Software\kingsoft\Office\WPP\AddinsWL] "项目名称"""2、visual studio 运行后&#xff0c;要选中附加到调试&#xff0c;并指定启动项目。 如PPT输入WPP搜…

Java锁到底是个什么东西

一、java锁存在的必要性 要认识java锁&#xff0c;就必须对2个前置概念有一个深刻的理解&#xff1a;多线程和共享资源。 对于程序来说&#xff0c;数据就是资源。 在单个线程操作数据时&#xff0c;或快或慢不存在什么问题&#xff0c;一个人你爱干什么干什么。 多个线程操…

【Go语言成长之路】创建Go模块

文章目录 创建Go模块一、包、模块、函数的关系二、创建模块2.1 创建目录2.2 跟踪包2.3 编写模块代码 三、其它模块调用函数3.1 修改hello.go代码3.2 修改go.mod文件3.3 运行程序 四、错误处理4.1 函数添加错误处理4.2 调用者获取函数返回值4.4 执行错误处理代码 五、单元测试5.…

SIMD学习笔记2:高斯卷积计算优化

https://github.com/gredx/simd-parallel-conv https://zhuanlan.zhihu.com/p/419806079 https://www.cnblogs.com/Imageshop/p/9069650.html https://zhuanlan.zhihu.com/p/308004749 https://zhuanlan.zhihu.com/p/83694328 SSE图像算法优化系列十八&#xff1a;三次卷积插值…

LeetCode、198. 打家劫舍【中等,一维线性DP】

文章目录 前言LeetCode、198. 打家劫舍【中等&#xff0c;一维线性DP】题目及分类思路线性DP&#xff08;一维&#xff09; 资料获取 前言 博主介绍&#xff1a;✌目前全网粉丝2W&#xff0c;csdn博客专家、Java领域优质创作者&#xff0c;博客之星、阿里云平台优质作者、专注…

假期2.6

一、填空题 1、一个类的头文件如下所示&#xff0c;num初始化值为5&#xff0c;程序产生对象T&#xff0c;且修改num为10&#xff0c;并使用show()函数输出num的值10。 #include <iostream.h> class Test { private: static int num; public: Test(int); void sho…

Python循环语句——for循环的基础语法

一、引言 在Python编程的世界中&#xff0c;for循环无疑是一个强大的工具。它为我们提供了一种简洁、高效的方式来重复执行某段代码&#xff0c;从而实现各种复杂的功能。无论你是初学者还是资深开发者&#xff0c;掌握for循环的用法都是必不可少的。在本文中&#xff0c;我们…