这段代码定义了一个名为 bubble_sort 的函数,接受一个可变的整数类型数组作为输入,然后使用嵌套的循环来实现冒泡排序。外部循环从数组的第一个元素开始迭代到倒数第二个元素,内部循环从数组的第一个元素开始迭代到倒数第二个元素。如果当前元素比下一个元素大,则交换它们的位置。在循环结束后,数组就会按升序排列。
在 main 函数中,我们定义了一个整数类型的数组,并将其传递给 bubble_sort 函数进行排序。最后,程序将输出排序后的数组
- fn bubble_sort(arr: &mut [i32]) {//参数是可变化的i32的数组
-
- let n = arr.len(); //获取arr的数组的长度,坐标从0开始
- for i in 0..n { //总循环是n次
- for j in 0..n-i-1 { //冒泡排序,每次处理一个减少一次。
- if arr[j] > arr[j+1] { //如果 前面的记录后面一个数值,交换,大值冒泡到后面
- arr.swap(j, j+1);
- }
- }
- }
- }
-
- fn main() {
- let mut arr = [5, 2, 9, 1, 5, 6,13,20,18];
- bubble_sort(&mut arr);
- println!("排序后的数组:{:?}", arr); // 输出 [1, 2, 5, 5, 6, 9]
- }

编写第一个代码,大家都会,但也要编写,目的是检测环境,安装了rust为1.72.1版本
- rustc --version
- rustc 1.72.1 (d5c2e9c34 2023-09-13)
运行基本的代码Hello_world代码,这个简单
代码为
- fn main(){
- let s="Hello world!";
- println!("{}",s);
-
- }
let为定义了一个s为字符串,赋值为Hello world!的字符串,fn为函数function的简写,main函数说明是函数的入口,类似C++和c语言,记住基本格式,打印println后面多了一个“!”,其他的类似c++的函数语言,后面用;进行语言结束。
没有意外是返回Hello world字符串
- fn Hello_world() ->&static str {
- let s="Hello world by keny!";
- return s;
-
- }
-
- fn main(){
- let Hello_world_str=Hello_world();
- println!("{}",Hello_world_str);
-
-
- }
还是Hello world的函数。定义了一个Hello_world的函数,函数直接返回字符串,通过main的函数进行调用这个定义的函数,运行结果是Hello world by keny
- warning: function `Hello_world` should have a snake case name
- --> src/main.rs:1:4
- |
- 1 | fn Hello_world() ->&'static str {
- | ^^^^^^^^^^^ help: convert the identifier to snake case: `hello_world`
- |
- = note: `#[warn(non_snake_case)]` on by default
-
- warning: variable `Hello_world_str` should have a snake case name
- --> src/main.rs:8:9
- |
- 8 | let Hello_world_str=Hello_world();
- | ^^^^^^^^^^^^^^^ help: convert the identifier to snake case: `hello_world_str`
-
- warning: `hello_world` (bin "hello_world") generated 2 warnings
- Finished dev [unoptimized + debuginfo] target(s) in 0.69s
- Running `target/debug/hello_world`
- Hello world by keny!
首先必须说明,Rust 是强类型语言,但具有自动判断变量类型的能力。这很容易让人与弱类型语言产生混淆。
如果要声明变量,需要使用 let 关键字。例如:
let a="abc";
不允许这样定义,说明a已经定义了字符串,后面有定义了float类型和int类型,实际是冲突的定义
- a = "abc";
- a = 4.56;
- a = 456;
检测的时候会提示
- warning: unused variable: `a`
- --> src/main.rs:6:9
- |
- 6 | let a=123.5;
- | ^ help: if this is intentional, prefix it with an underscore: `_a`
-
- warning: unused variable: `a`
- --> src/main.rs:8:9
- |
- 8 | let a=123;
- | ^ help: if this is intentional, prefix it with an underscore: `_a`
-
- warning: unused variable: `a`
- --> src/main.rs:10:9
- |
- 10 | let a=true;
- | ^ help: if this is intentional, prefix it with an underscore: `_a`
当然,使变量变得"可变"(mutable)只需一个 mut 关键字。
- let mut a=234;
- a=567;
如果这样定义
- let a=234;
-
- let a=456;
-
- 会编译警告;“`#[warn(unused_variables)]` on by default”
- let a = 2;
- let a=a+1;
- let a=a*a;
- let a=a*a*a;
- println!("{}",a);
重影与可变变量的赋值不是一个概念,重影是指用同一个名字重新代表另一个变量实体,其类型、可变属性和值都可以变化。但可变变量赋值仅能发生值的变化。