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

ops/2025/2/26 19:55:22/

文章目录

    • 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/ops/161482.html

相关文章

VIP商品页面结构经常变化怎么办?

在爬取VIP商品详情时&#xff0c;页面结构的频繁变化是常见的挑战。为了应对这一问题&#xff0c;可以采取以下策略&#xff1a; 1. 使用稳定的选择器 在编写爬虫时&#xff0c;尽量选择更通用、更稳定的CSS选择器或XPath表达式&#xff0c;避免依赖于容易变化的元素属性。例…

kafka队列堆积问题的常见排查

1. 检查生产者和消费者的速率 生产者吞吐量测试&#xff1a; kafka-producer-perf-test.sh --topic <your-topic> # 需要填写测试的主题名&#xff0c;如 "my-topic" --num-records <count> # 需要填写消息的数量&#xff08;例如&#xff1a;100000…

FFmpeg.NET:.NET 平台上的音视频处理利器

FFmpeg.NET 是一个封装了 FFmpeg 功能的 .NET 库&#xff0c;能够方便地在 C# 项目中处理音视频文件。它支持多种操作&#xff0c;包括转码、剪辑、合并、分离音频等。 功能 解析元数据从视频生成缩略图使用以下参数将音频和视频转码为其他格式&#xff1a; 码率&#xff08;…

检查SSH安全配置-sshd服务端未认证连接最大并发量配置

介绍 MaxStartups参数指到SSH守护进程的未经身份验证的最大并发连接数。 逻辑依据 为防止系统因大量待处理的身份验证连接尝试而出现拒绝服务的情况&#xff0c;请使用 MaxStartups 的速率限制功能来保护 sshd 登录的可用性&#xff0c;并防止守护进程不堪重负。 检查方法 …

linux 网卡配置

linux网卡可以通过命令和配置文件配置,如果是桌面环境还可以通过图形化界面配置. 1.ifconfig(interfaces config)命令方式 通常需要以root身份登录或使用sudo以便在Linux机器上使用ifconfig工具。依赖于ifconfig命令中使用一些选项属性&#xff0c;ifconfig工具不仅可以被用来…

WPS中如何对word表格中数据进行排序,就像Excel排序那样简单

大家好&#xff0c;我是小鱼。 word表格数据能进行排序吗&#xff1f;就像Excel一样进行排序。全可以对Word表格中的笔画、数字、拼音、日期数据进行排序操作&#xff0c;对数据排序并不是Excel表格的专利&#xff0c;Word表格文档同样可以做到。分享一下对在WPS中对Word表格数…

Windows获取字体文件

// 包含必要的头文件 #include <string> #include <set> #include <vector> #include <iostream> #include <filesystem> #include <windows.h> #include <fstream> // 用于文件操作 #include <algorithm> // 确保包含 std::m…

flink系列之:使用flink cdc3从mysql数据库同步数据到doris和starrocks

flink系列之&#xff1a;使用flink cdc3从mysql数据库同步数据到doris和starrocks 一、下载部署flink二、下载部署flink cdc3三、下载mysql-connector-java到flink和flink cdc的lib目录四、flink设置checkpoint支持增量同步数据五、mysql到doris和starrocks的yaml配置文件六、启…