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

news/2025/2/23 17:42:36

文章目录

    • 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; // f64
        let 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.niftyadmin.cn/n/5863627.html

相关文章

蓝桥备赛(一)- C++入门(上)

一、工具安装 Dev-C安装&#xff1a;https://www.bilibili.com/video/BV1kC411G7CS 一般比赛会用到Dev-C, 但是Dev-C还是有自身的局限性 &#xff0c; 后续的博客学习中 &#xff0c; 必要的时候 &#xff0c; 会使用VS2022 &#xff0c; 下面是VS2022的安装和使用教程。 VS202…

Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用

在Go中使用Viper将YAML配置绑定到结构体时&#xff0c;主要依赖 mapstructure 标签&#xff08;而非 json 或 yaml 标签&#xff09;实现字段名映射。 --- ### 1. **基础绑定方法** 使用 viper.Unmarshal(&config) 或 viper.UnmarshalKey("key", &subConfi…

基于FISCO-BCOS搭建第一个区块链网络

一、前言介绍&#xff1a; 本篇博客以Ubuntu虚拟机为例 本篇博客我会大致介绍“搭建第一个区块链网络”的搭建过程&#xff0c;具体的还是要查看FISCO-BCOS的官方文档。会着重介绍在搭建过程中可能遇到的一些报错&#xff0c;以及解决报错的常用方法。 参考FISCO-BCOS的官方文档…

Android14 Camera框架中Jpeg流buffer大小的计算

背景描述 Android13中&#xff0c;相机框架包含对AIDL Camera HAL的支持&#xff0c;在Android13或更高版本中添加的相机功能只能通过AIDL Camera HAL接口使用。 对于Android应用层来说&#xff0c;使用API34即以后版本的Camera应用程序通过Camera AIDL Interface访问到HAL层…

TCP/UDP调试工具推荐:Socket通信图解教程

TCP/UDP调试工具推荐&#xff1a;Socket通信图解教程 一、引言二、串口调试流程三、下载链接 SocketTool 调试助手是一款旨在协助程序员和网络管理员进行TCP和UDP协议调试的网络通信工具。TCP作为一种面向连接、可靠的协议&#xff0c;具有诸如连接管理、数据分片与重组、流量和…

@media 的常用场景与示例

media 的常用场景与示例 1. 基本概念2. 常用场景2.1 不同屏幕宽度的布局调整2.2 隐藏或显示元素2.3 字体大小调整2.4 图片大小调整2.5 高度调整2.6 颜色调整2.7 鼠标悬停效果 3. 常用示例3.1 基本响应式布局3.2 隐藏侧边栏3.3 字体大小和图片大小 4. 总结 在现代网页设计中&…

【架构】事件驱动架构(Event - Driven Architecture,EDA)

一、事件驱动架构理论基础 事件驱动架构(Event - Driven Architecture,EDA)是一种软件设计范式,事件驱动的体系结构由生成事件流、侦听这些事件的事件使用者以及将事件从生成者传输到使用者的事件通道组成。 在事件驱动架构中,系统的行为由事件触发。事件可几乎实时发送,…

苹果确认iOS 18.4四月初推出:Apple Intelligence将迎来中文支持

在科技飞速发展的当下&#xff0c;人工智能&#xff08;AI&#xff09;已经成为智能设备领域的核心竞争力之一。苹果公司作为全球科技行业的领军者&#xff0c;其在AI领域的每一步动作都备受关注。2025年2月20日&#xff0c;苹果公司正式宣布&#xff0c;将于4月初推出iOS 18.4…