Skip to content
Published at:

Common Programming Concepts

Variables and Mutability

变量声明

变量和可变性

变量默认是不可变的(immutable),rust鼓励你使用不可变变量

常量:永久不可变,需要指定类型,需要在编译期能确定值,生命周期和整个程序的一样

变量遮蔽(Shadowing)

数据类型

标量类型

整型

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

Note: isizeusize依赖于架构,64位架构是64位,32位架构是32位. 主要用作当集合的索引,长度

字面值表示方式

Number literalsExample
Decimal98_222
Hex0xff
Octal0o77
Binary0b1111_0000
Byte (u8 only)b'A'

浮点型

关键字f32f64,采用IEEE-754标准,字面值默认是f64

布尔类型

字符类型

char:用单引号表示,大小为4个bytes,代表一个Unicode标量值

Unicode标量值包含从U+0000到U+D7FF和U+E000到U+10FFFF在内的值,

复合类型

元组类型(tuple)

是一个将多个其他类型的值组合刊一个复合类型的主要方式,元组长度固定,一旦声明,其长度不会增加或减少

  • 获取里面的元素:通过索引index
  • 解构(destructure):通过模式匹配
rust
fn main() {
    // 1.定义一个元组
    let tup: (i32, f64, u8) = (500, 6.4, 1);

    // 2.获取里面的元素
    let x: (i32, f64, u8) = (500, 6.4, 1);
    let five_hundred = x.0;
    let six_point_four = x.1;
    let one = x.2;

    // 3.解构
    let tup = (500, 6.4, 1);
    let (x, y, z) = tup;
    println!("The value of y is: {}", y);
}

数组类型

数组:类型相同,长度固定

  • 定义方式
  • 索引
  • 编译期检查越界
rust
fn main() {
    // 1.定义一个数组
    let a = [1, 2, 3, 4, 5];
    let months = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
    ];
    let a: [i32; 5] = [1, 2, 3, 4, 5];
    let a = [3; 5]; // 初始值是3,有5个元素,等同于下面定义
    let a = [3, 3, 3, 3, 3];

    // 2.通过索引获取里面元素
    let a = [1, 2, 3, 4, 5];
    let first = a[0];
    let second = a[1];

    // 3.编译期检查越界
    let a = [1, 2, 3, 4, 5];
    let index = 10;
    let element = a[index];
    println!("The value of element is: {}", element);
}

函数

Rust是一门基于表达式的语言

语句(Statements)和表达式(Expressions)

语句:执行一些操作,但不返回值的指令

表达式:计算并产生一个值

分号;是表示语句的结束. 加了分号就变成了语句,不会有返回值;不加分号就是表达式,会有返回值

注释

普通注释

用快捷键生成,不用记忆

文档注释

后面讲

控制流

if表达式

  • if
  • else if
  • if let
rust
fn main() {
    // 1.if
    let number = 3;

    if number < 5 {
        println!("condition was true");
    } else {
        println!("condition was false");
    }

    // 2.if else if
    let number = 6;

    if number % 4 == 0 {
        println!("number is divisible by 4");
    } else if number % 3 == 0 {
        println!("number is divisible by 3");
    } else if number % 2 == 0 {
        println!("number is divisible by 2");
    } else {
        println!("number is not divisible by 4, 3, or 2");
    }

    // 3.if let
    let condition = true;
    let number = if condition { 5 } else { 6 };

    println!("The value of number is: {}", number);
}

循环表达式

  • 普通 loop
  • 带返回值的 loop
  • while 循环
  • for in 循环
rust
fn main() {
    // 1.循环
    loop {
        println!("again!");
    }

    // 2.循环带返回值
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    println!("The result is {}", result);

    // 3.循环:带判断条件
    let mut number = 3;

    while number != 0 {
        println!("{}!", number);
        number -= 1;
    }

    println!("LIFTOFF!!!");

    // 4.1 for in循环
    let a = [10, 20, 30, 40, 50];

    for element in a.iter() {
        println!("the value is: {}", element);
    }

    // 4.2 for in循环
    for number in (1..4).rev() {
        println!("{}!", number);
    }
    println!("LIFTOFF!!!");
}

模式解构

  • tuple
  • struct
  • tuple struct
  • enum
rust
struct Person(String, i32);

struct Point {
    x: i32,
    y: i32,
}

fn foo() {
    let p = Person(String::from("shibin"), 18);
    let Person(name, age) = p;

    println!("-------------------");
    let p = Point { x: 10, y: 10 };
    let Point { x, y } = p;
    println!("x = {:?}", x);
}

类型推导

Rust只允许“局部变量/全局变量”实现类型推导,而函数签名等场 景下是不允许的

类型别名

rust
// `NanoSecond` 是 `u64` 的新名字。
type NanoSecond = u64;
type Inch = u64;

type Age = u32;

静态变量

变量的生命周期是整个程序,从启动到退出

rust
static GLOBAL: i32 = 0;

常量

不可变的变量

rust
const GLOBAL: i32 = 0;

Data Types

基本数据类型

  • bool
  • char
  • 整数类型
  • 浮点类型
  • 指针类型

char

现代语言,没有历史包袱, 它可以描述任何一个符合unicode标准的字符值

整数类型

整数类型在符号无符号
8 bitsi8u8
16 bitsi16u16
32 bitsi32u32
64 bitsi64u64
128 bitsi128i128
Pointer sizeisizeusize

默认为i32类型(“缺省”类型)

前缀声明(0x,0o,0b)

后缀类型声明

数字中的_字符

整数溢出

默认情况下,在debug模式 下编译器会自动插入整数溢出检查,一旦发生溢出,则会引发panic; 在release模式下,不检查整数溢出,而是采用自动舍弃高位的方式。

浮点类型

Rust提供了基于IEEE 754-2008标准的浮点类型; 分别为f32和f64, 默认f64

指针类型

https://doc.rust-lang.org/reference/types/pointer.html

  • References (& and &mut)
  • Shared references (&)
  • Mutable references (&mut)
  • Raw pointers (*const and *mut)
  • Smart pointer
    • Box<T> for allocating values on the heap
    • Rc<T>, a reference counting type that enables multiple ownership
    • Ref<T> and RefMut<T>, accessed through RefCell<T>, a type that enforces the borrowing rules at runtime instead of compile time

复合数据类型

  • tuple
  • unit(单元类型:tuple中一个元素也没有)
  • struct
  • tuple struct
  • enum
  • union

模式匹配

tuple、struct、struct tuple对比

类型名称tuplestructstruct tuple
语法没有名字+圆括号名字+大括号名字+圆括号
类型名字没有单独的名字有单独的名字有单独的名字
成员名字没有单独的名字有单独的名字没有单独的名字

enum

可 以像空结构体一样,不指定它的类型;也可以像tuple struct一样,用圆 括号加无名成员;还可以像正常结构体一样,用大括号加带名字的成 员。

union

Rust里面也支持union类型,这个类型与C语言中的union完全一 致。但在Rust里面,读取它内部的值被认为是unsafe行为,一般情况下 我们不使用这种类型。它存在的主要目的是为了方便与C语言进行交 互。