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

devtools/2025/2/26 15:48:39/

文章目录

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

Variables and Mutability

rust">fn main() {let mut x = 5;println!("The value of x is: {}", x);x = 6;println!("The value of x is: {}", x);
}
rust">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

    rust">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.

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

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

      rust">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)

    rust">fn main() {let a = [1, 2, 3, 4, 5];
    }
    
    rust">let a: [i32; 5] = [1, 2, 3, 4, 5];
    
    rust">let a = [3; 5];
    
    rust">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.

rust">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
rust">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.
rust">fn main() {let x = 5;let y = {let x = 3;x + 1};println!("The value of y is: {}", y);
}

This expression:

rust">{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.

rust">fn five() -> i32 {5
}fn main() {let x = five();println!("The value of x is: {}", x);
}
rust">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

rust">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.

rust">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.

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

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

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

http://www.ppmy.cn/devtools/162830.html

相关文章

【JavaWeb12】数据交换与异步请求:JSON与Ajax的绝妙搭配是否塑造了Web的交互革命?

文章目录 &#x1f30d;一. 数据交换--JSON❄️1. JSON介绍❄️2. JSON 快速入门❄️3. JSON 对象和字符串对象转换❄️4. JSON 在 java 中使用❄️5. 代码演示 &#x1f30d;二. 异步请求--Ajax❄️1. 基本介绍❄️2. JavaScript 原生 Ajax 请求❄️3. JQuery 的 Ajax 请求 &a…

kotlin 知识点 七 泛型的高级特性

对泛型进行实化 泛型实化这个功能对于绝大多数Java 程序员来讲是非常陌生的&#xff0c;因为Java 中完全没有这个概 念。而如果我们想要深刻地理解泛型实化&#xff0c;就要先解释一下Java 的泛型擦除机制才行。 在JDK 1.5之前&#xff0c;Java 是没有泛型功能的&#xff0c;…

Linux环境基础开发工具的使用(apt、vim、gcc、g++、gdb、make/Makefile)

Linux环境基础开发工具的使用&#xff08;apt、vim、gcc、g、gdb、make/Makefile&#xff09; 文章目录 Linux软件包管理器 - apt Linux下安装软件的方式认识apt查找软件包安装软件如何实现本地机器和云服务器之间的文件互传卸载软件 Linux编辑器 - vim vim的基本概念vim下各…

将DeepSeek接入vscode的N种方法

接入deepseek方法一:cline 步骤1:安装 Visual Studio Code 后,左侧导航栏上点击扩展。 步骤2:搜索 cline,找到插件后点击安装。 步骤3:在大模型下拉菜单中找到deep seek,然后下面的输入框输入你在deepseek申请的api key,就可以用了 让deepseek给我写了一首关于天气的…

【高屋建瓴】彻底理解windows和linux的库连接

在 Linux 下&#xff0c;与 Windows 的 .lib&#xff08;静态库、导入库&#xff09;和 .dll&#xff08;动态库&#xff09; 对应的库文件类型如下&#xff1a; WindowsLinux说明静态库 (.lib)静态库 (.a)静态链接库&#xff0c;编译时直接将代码合并到可执行文件中&#xff…

linux-c 字节序问题--大小端

今天面试被问了一个网络字节系列的问题分享一下&#xff1a; 1.如何将Int转换成byte数组在网络上传输。 2.计算机世界里的大小端问题。 计算机世界里为什么有大小端 硬件设计因素 CPU 架构差异 不同的 CPU 架构在设计时&#xff0c;对于多字节数据在内存中的存储顺序…

基于Java(SpringBoot)+MySQL+Vue实现博客系统+社区

本来是想着写一博客系统的&#xff0c;后来写着写着就变成了一个“四不像”——介于博客和社区之间的一个东西。 start 数据库名称为 graduation 结构&#xff1a; graduation_admin 后台管理页面 (vue)graduation_web 前台页面 (vue)graduation_server 后台api (Java) 1.…

力扣 颜色分类

双指针&#xff0c;滑动窗口&#xff0c;排序。 题目 简单做法&#xff0c;单指针&#xff0c;一直遍历&#xff0c;先排小再排大。找到是0的与指针指的位置做交换&#xff0c;交换后指针在这个位置的任务就结束了&#xff0c;接着去定住下一个&#xff0c;然后依次遍历完一趟…